[英]Why does my len() code in python not provide the correct length of a string?
I'm trying to code a hangman game using python and I'm having issues getting the correct length of a string to return when I run the code.我正在尝试使用 python 编写一个刽子手游戏,但在运行代码时无法获取正确长度的字符串以返回。 It will return things like ['clouds'] 10
or ['mango'] 9
or ['rose'] 8
when it should actually be returning ['clouds'] 6
and ['mango'] 5
and ['rose'] 4
.它会返回['clouds'] 10
或['mango'] 9
或['rose'] 8
,而实际上它应该返回['clouds'] 6
和['mango'] 5
和['rose'] 4
.
Please help me see what I'm doing wrong!请帮我看看我做错了什么!
Here's what I wrote:这是我写的:
import random
word_list = ['tiger','dog','cake','disney','donut','rose','clouds','movies','sparkle','yoga','walrus','candle','mango','taco','flowers']
word = str(random.sample(word_list, 1))
word_len = len(word)
print(word, word_len)
random.sample(word_list, 1)
returns single item list
like ["sparkle"] and you're converting it into str
so it adds [""]
around the word so word becomes '["sparkle"]'
random.sample(word_list, 1)
返回单项list
如 ["sparkle"] 并且您将其转换为str
因此它在单词周围添加[""]
因此单词变为'["sparkle"]'
I think you need:我认为你需要:
import random
word_list = ['tiger','dog','cake','disney','donut','rose','clouds','movies','sparkle','yoga','walrus','candle','mango','taco','flowers']
word = random.sample(word_list, 1)
word_len = len(word[0])
print(word, word_len)
Output:输出:
['sparkle'] 7
You're using wrong method你使用了错误的方法
import random
word_list = ['tiger','dog','cake','disney','donut','rose','clouds','movies','sparkle','yoga','walrus','candle','mango','taco','flowers']
# return a k length list of unique elements chosen from the population sequence or set
# where k is 1, population sequence is word_list
print(random.sample(word_list, 1))
# to get random item from list you have to use random.choice
print(random.choice(word_list))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.