简体   繁体   English

Python如何在用户输入中查找字符数

[英]Python how to find the number of characters in the user input

im creating a sort of quiz game on python and one of the questions is 'type a word that has 5 letters in them'. 我在python上创建了一种问答游戏,其中一个问题是“键入一个包含5个字母的单词”。

so basicaly what i want is for the user to type anything that has 5 letters or characters in them.and then python checks if it has 5 letters and if it is correct it sends them to the next question. 所以基本上我想要的是用户键入任何包含5个字母或字符的东西。然后python检查是否有5个字母,如果正确,它将把它们发送到下一个问题。

For your game, i assume you have some while loop that keeps things rolling. 对于您的游戏,我假设您有一些while循环可以使事情继续进行。

Do this: 做这个:

word = input("Give me a 5 letter word: ")

The line above will ask the user for the 5 letter word and their input will be stored in the variable word. 上面的行将要求用户输入5个字母的单词,并且他们的输入将存储在可变单词中。 Then check 然后检查

if len(word) != 5:
    print "that's not 5 letters..."

You could try this. 你可以试试看。

if len(word) is 5

EDIT 编辑
Apparently this is bad. 显然这很糟糕。 I did not know at the time of posting. 发布时我还不知道。 Anyway for those who are unaware and curios, here is a little experiment 无论如何,对于那些没有意识和好奇的人,这是一个小实验

>>> a = "hello"
>>> len(a) is 5
True
>>> len(a) is 4
False
>>> len(a) is 5.0
False
>>> len(a) == 5
True
>>> len(a) == 4
False
>>> len(a) == 5.0
True

EDIT again Based on a comment by interjay, I further did an experiment. 再次编辑根据interjay的评论,我进一步进行了实验。

>>> for i in range(1000):
...     a = 'x'*i
...     if len(a) is not i:
...             print(i)
...             break
... 
257

If someone could explain why it works up to 256, I'd love to add it here 如果有人可以解释为什么它最多可以支持256个,我很乐意在这里添加它

EDIT Once more 再次编辑
This probably explains the behavior. 这可能可以解释行为。 I am quoting interjay from the comments. 我在评论中引用了interjay。

It's an optimization in CPython: Objects for the integers in the range -1 to 256 are preallocated, and each time one of these values is encountered, it is given the same object. 这是CPython中的一种优化:-1到256范围内的整数的对象已预先分配,并且每次遇到这些值之一时,都会为其分配一个相同的对象。 For other integers, a new object is created each time. 对于其他整数,每次都会创建一个新对象。 Of course, this is an implementation detail and can change between Python versions. 当然,这是一个实现细节,可以在Python版本之间进行更改。

answer = raw_input("What is a five letter word? ")

if len(answer) == 5:
    print "Correct!"
else:
    print "Wrong, that has", len(answer), "letters!"

If you are using Python 3 you would need to replace raw_input with input and put parentheses around the print expressions (because print becomes a function). 如果您使用的是Python 3,则需要用input替换raw_input并在打印表达式周围加上括号(因为print成为函数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM