【发布时间】:2020-07-29 15:37:57
【问题描述】:
我是编程新手,正在尝试制作基本的刽子手游戏。由于某种原因,在从文本文件计算字符串的长度时,某些单词的字符串长度计算不正确。有些字符串的值太高,有些太低。我似乎无法弄清楚为什么。我已经确保文本文件中没有空格,所以空格算作一个字符。
import random
#chooses word from textfile for hangman
def choose_word():
words = []
with open("words.txt", "r") as file:
words = file.readlines()
#number of words in text file
num_words = sum(1 for line in open("words.txt"))
n = random.randint(1, num_words)
#chooses the selected word from the text file
chosen_word = (words[n-1])
print(chosen_word)
#calculates the length of the word
len_word = len(chosen_word)
print(len_word)
choose_word()
#obama returns 5
#snake, turtle, hoodie, all return 7
#intentions returns 11
#racecar returns 8
words.txt
snake
racecar
turtle
cowboy
intentions
hoodie
obama
【问题讨论】:
-
如果您执行
print(words),那么您很可能会发现问题。最可能发生的事情是字符串末尾有一个换行符。所有人,除了最后一位,这是唯一正确的一位!
标签: python string-length