How to Shorten URLs in Python using pyshorteners (TinyURL Example)

How to Shorten URLs in Python

How to Shorten URLs in Python

Learn to convert long URLs into short links with simple Python code

Introduction

Long URLs can be difficult to share or remember. Fortunately, Python makes it easy to shorten URLs using libraries like pyshorteners. In this article, you’ll learn how to convert a long link into a shorter one quickly and easily.

Example: Shortening URL using Python

First, install the pyshorteners package:

pip install pyshorteners

Classes and Methods Used

Class / Function Type
Pyshorteners class
tiny function
short(str: URL) function

Here’s an example Python script that takes a long URL and generates a short one using TinyURL:


import pyshorteners as ps
# Initialize the shortener
obj = ps.Shortener()
# Enter your long URL here
print("Enter the Long URL: ")
inp=input()
# Shorten the URL using TinyURL
result = obj.tinyurl.short(inp)
# Print the shortened URL
print("Short URL:", result)

    

Result

Output of Python program

Comments