Python: How to count number of letters in a string?


See question above. I'm having trouble on the exercise "Ending Up"


The simplest way is to use the built in function, len().

a = "some string"
print len(a)       # 11

To determine if a string is not empty, ("")

if len(a) > 0:

since an empty string has no length.


You may either use Python's built-in len() function or define your own.

text = "Number of characters in this text"
print len(text)

Custom function

def count_chars(txt):
	result = 0
	for char in txt:
		result += 1     # same as result = result + 1
	return result

print count_chars(text)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.