python - 删除 python 中的换行符?

标签 python line-breaks

我正在开发一个简单的 Python 游戏,在该游戏中,玩家尝试猜测单词中包含的字母。问题是,当我打印一个单词时,它会在末尾打印\n 。

根据我最初的研究,我认为我需要使用 r.string() 来删除它。但是,我不确定它会去哪里。

抱歉新手问题。

import random
with open('wordlist.txt') as wordList:
    secretWord = random.sample(list(wordList), 1)

print (secretWord)

最佳答案

我认为其他答案更好,但您也可以使用:

secretWord = secretWord.replace('\n', ''))

编辑:OP 声明 secretWord 是一个列表,而不是一个字符串。

对于字符串列表,使用:

secretWord = [each.replace('\n', '') for each in secretWord]

关于python - 删除 python 中的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774490/

相关文章:

python - 将Python中的负索引转换为正索引

Python MySQL 连接器 : caching_sha2_password plugin

Python,比较和计算列表中的数据

ios - 带有换行和自动布局的 UIButton

python - 如何悄悄启动Python REPL?

python - 使用 gzip 和 pickle 时出现 UnicodeDecodeError

html - 在 flexbox 的图像下居中文本/内容?

regex - 使用 jQuery Datatables 2016 将带有换行符的值导出到 Excel 中的单个单元格中

string - 多行字符串文字仅在 REPL 和 Worksheet 中表现正常

python - 将换行符添加到 Python 编写的 json