我试图从文件中读取一个单词并随机选择一个单词。我可以选择一个随机单词,但是一些单词在单词之后有额外的空格,例如缩进。我该如何删除?
import random
random_word = []
secret_word = []
def choose_secret_word():
infile = open("words.txt")
for every_item in infile:
random_word.append(every_item)
secret_word = random.choice(random_word)
print(secret_word)
choose_secret_word()
我想你需要strip()
例:
print(secret_word.strip())
使用.strip()
import random
random_word = []
secret_word = []
def choose_secret_word():
infile = open("words.txt")
for every_item in infile:
random_word.append(every_item.strip())
secret_word = random.choice(random_word)
print(secret_word)
choose_secret_word()
我认为将rstrip()应用于你的单词应该有效:https://docs.python.org/3/library/stdtypes.html#str.rstrip
所以你可以这样做:secret_word = random.choice(random_word).rstrip()
我会对你的代码应用一个rstrip()方法:
secret_word.rstrip()
更多的出轨:https://www.tutorialspoint.com/python/string_rstrip.htm干杯