How to find the length of a string in Python

In Python, a string is a sequence of characters that is used to represent textual data. There are multiple ways to get the length of a string. Here are some of the most common methods:

Using the len() function:

Syntax
len(string)

Return: Returns an integer value which is the length of the string

The len() function is a built-in function in Python that returns the length of a string.

my_string = "Python!!!" string_length = len(my_string) print(string_length) # Output: 9

Using a for loop:

You can also use a for loop to iterate over each character in the string and count the number of characters.

my_string = "Python!!!" string_length = 0 for char in my_string: string_length += 1 print(string_length) # Output: 9

Using a while loop:

You can also use a while loop to iterate over each character in the string and count the number of characters.

my_string = "Python!!!" string_length = 0 while my_string[string_length:]: string_length += 1 print(string_length) # Output: 9

Note that all of these methods will give you the same result, but using the len() function is the most efficient and commonly used method.

Python string

Python string is a built-in data type in Python, and it is represented by the str class. Strings can contain letters, numbers, symbols, and spaces.

Strings in Python are immutable, which means that once a string is created, you its contents. However, you can create a new string that is a modified version of the original string.

Python provides a large number of built-in string methods that you can use to manipulate strings. These methods allow you to perform operations such as finding substrings, replacing text, splitting a string into substrings, and joining substrings into a single string.