【问题标题】:is there a reason why the len function displays the wrong lengh of a word (no spaces etc.)?len 函数显示错误的单词长度(没有空格等)是否有原因?
【发布时间】:2021-03-24 09:49:32
【问题描述】:

以下场景:我想显示从简单的 .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 文件中没有任何空格

提前致以诚挚的问候和非常感谢

【问题讨论】:

  • 你没有阅读你的文件内容
  • 据我所知,我是。当我打印 secret_word 时,它会显示 .txt 文件中的随机单词
  • 是的,我的错,你读了它,但这不是 Python 的阅读方式。使用withstrip 读取行尾
  • 你能展示一下如何用“with”和“strip”修改上面显示的代码吗?我只是好奇,虽然 anonymus1994.1 的解决方案已经很好了

标签: import output character string-length


【解决方案1】:

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

对于您的问题:您能否粘贴您正在使用的完整代码?我尝试了您的示例,它显示了每个单词的正确长度(换行符为 + 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"

【讨论】:

  • 首先:您完全正确,应该也提到语言...我是新来的-下次我会做得更好其次:谢谢!它现在正在工作。 .strip() 是解决方案!
猜你喜欢
  • 1970-01-01
  • 2019-10-20
  • 2014-05-17
  • 2022-11-02
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 2021-11-02
相关资源
最近更新 更多