How to Count Characters in Python
Strings and lists represent fundamental data types for Python programmers. Both contain collections of data: string contain collections of characters that form a sentence, and lists contain collections of various types of data intermixed. If you treat a string like a list, you can perform operations on it, like determining how many characters it holds, or how many of a particular kind of character it contains.
Instructions
-
-
1
Create a string. The string can contain an arbitrary amount of characters such as numbers, letters, punctuation, and whitespace:
>>>x = 'This is a, string'
-
2
Get the length of the string using the "len) function. This function returns the total amount of characters in the string:
>>>len(x)
17 -
-
3
Count only the characters and punctuation. It may be the case that you don't want to count whitespace. In this instance, create a "for" loop to count each item, only counting it if it is not whitespace:
>>>y = 0
>>>for item in x:
. . . if item = ' ':
. . . pass
. . . else:
. . . y += 1
>>>y
14
-
1