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

Estimated read time 2 min read

To count the number of characters in a string input in Python, you can use the same methods as mentioned before, but instead of assigning a string value to a variable, you can use the built-in input() function to get the string input from the user. Here’s an example code:

string = input("Enter a string: ")
print(len(string))

In this example, the input() function is used to get a string input from the user and store it in the string variable. The len() function is then used to count the number of characters in the string variable, and the result is printed to the console.

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

string = input("Enter a string: ")
count = 0
for char in string:
    count += 1
print(count)

In this example, the input() function is used to get a string input from the user and store it in the string variable. The for loop then 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.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply