简体   繁体   中英

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. 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 .

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"]'

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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