Python program to calculate the length of a string

Learn to calculate the length of a string in Python 3.

Python program to calculate the length of a string

Method 1 - Simple for loop

Code

user_input = input("Provide a string ==> ")
length = 0
for char in user_input:
    length += 1
print(f"Length of '{user_input}' is {length}")

Output

Provide a string ==> Joe Biden
Length of 'Joe Biden' is 9

Method 2 - Using len() built-in function

Code

user_input = input("Provide a string ==> ")
print(f"Length of '{user_input}' is {len(user_input)}")

Output

Provide a string ==> Pylenin
Length of 'Pylenin' is 7

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe