How to find the length of a string in Python?
In Python, finding the length of a string is straightforward and can be done using the built-in len()
function. This function returns the number of characters in a string, including spaces, punctuation, and special characters. Here’s how you can use it:
Using the len()
Function
The len()
function is one of Python's built-in functions, and it doesn't only work for strings; it can also determine the length of other iterable data types, such as lists, tuples, dictionaries, and more. Here’s how to use len()
to find the length of a string:
# Define a string my_string = "Hello, world!" # Use the len() function to find the length of the string string_length = len(my_string) # Print the length print("The length of the string is:", string_length)
This code will output:
The length of the string is: 13
Example Details
my_string
is a string variable containing the text"Hello, world!"
.len(my_string)
computes the number of characters inmy_string
, which includes all letters, punctuation marks, and spaces.- The result,
13
, is stored in the variablestring_length
. - The
print()
function is then used to display the length.
Additional Considerations
-
Empty Strings: If the string is empty,
len()
returns0
.empty_string = "" print(len(empty_string)) # Output: 0
-
Unicode Characters: The
len()
function counts Unicode characters effectively. Each character, regardless of its complexity, counts as one.unicode_string = "你好世界" # "Hello world" in Chinese print(len(unicode_string)) # Output: 4
-
Special Characters: Special characters and escape sequences such as newline (
\n
) or tab (\t
) are also counted as a single character.special_string = "Line1\nLine2" print(len(special_string)) # Output: 11
-
Strings with Emojis: Emojis or other composite characters are counted based on how they are represented in Python. Usually, each symbol is counted as one character.
emoji_string = "Hello 👋🌍" print(len(emoji_string)) # Output will depend on the representation but likely is 9
The len()
function is a simple and efficient way to determine the length of a string in Python, making it a commonly used tool for string manipulation and processing tasks.
GET YOUR FREE
Coding Questions Catalog