I have a Python 3.4.1 question
I am wondering if it is possible to put in a word, via input(), and find the number of letters in the word you inputed .
For example: Python, 6 letters.
My regards, James
You're looking for the len method, which works on any object with a definable length:
>>>test_string = "Hello"
Hello
>>>len(test_string)
5
For a string, it will treat the string as a list of characters. This means "Hello" has 5, but "Hello " would have 6, and "Hello World!" would have 12.
The input command reads the value as python code rather than a string input. For example, if you have:
def Python():
print "it enters this method"
word = input("Enter a word: ")
word()
It will grab the input from the user (in this case, let's say you enter Python), and convert it to code. Therefore, word() would be Python() rather than "Python"().
There's 2 ways around this. Firstly, you could do the inconvenient method and enter the word in with quotes (so when asked for input, you write "Python" rather than Python). This will read it in as a string.
The more reasonable way of doing this is using raw_input:
word = raw_input("Enter a word: ")
From there, you simply use the len() method:
length = len(word)
print length