How to Count the Number of Characters in a String in Python?

Estimated read time 1 min read

To count the number of characters in a string in Python, you can use the built-in len() function. Here’s an example code:

string = "Hello, world!"
print(len(string))

In this example, the len() function is used to count the number of characters in the string variable named string. The result is then printed to the console, which outputs 13 since there are 13 characters in the string.

You can also use a for loop to iterate through each character in the string and increment a counter variable. Here’s an example code:

string = "Hello, world!"
count = 0
for char in string:
    count += 1
print(count)

In this example, the for loop iterates through each character in the string variable named string and increments the count variable by 1 for each character. The final count is then printed to the console, which outputs 13 since there are 13 characters in the string.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply