len 函数显示错误的单词长度(没有空格等)是有原因的吗?

is there a reason why the len function displays the wrong lengh of a word (no spaces etc.)?

以下场景:我想显示从一个简单的 .txt 列表中选择的随机单词的长度,如下所示:

composer
circulation
fashionable
prejudice
progress
salesperson
disappoint

我使用以下代码显示列表中的这些单词之一:

random_word_generator = open("random_words.txt", "r")
random_words = list(random_word_generator)
secret_word = random.choice(random_words)

然而,每当我想通过使用打印单词的长度时:

print("My secret word is " + str(len(secret_word)))

显示单词的长度 - 1个字符

喜欢:

progress --> 应该是 8 个字母,但是 python 显示 7...

你知道如何解决这个问题吗?

顺便说一句:我的 .txt 文件中没有任何空格

谨致问候并提前致谢

您应该在标题和标签中提及您使用的语言。

针对您的问题:能否粘贴您正在使用的完整代码?我试过你的例子,它显示了每个单词的正确长度(换行符 + 1,你可以通过调用 .strip() 删除它),所以我猜你做了一些不同的事情。

random_word_generator = open("random_words.txt", "r")
random_words = list(random_word_generator) # ['composer\n', 'circulation\n', 'fashionable\n', 'prejudice\n', 'progress\n', 'salesperson\n', 'disappoint\n']
secret_word = random.choice(random_words) # "progress\n"
print("My secret word is " + str(len(secret_word))) # "My secret word is 9"
print("My secret word w/o newline is " + str(len(secret_word.strip()))) # "My secret word w/o newline is 8"