当从文件中读取时,如何摆脱额外的空间

问题描述 投票:1回答:4

我试图从文件中读取一个单词并随机选择一个单词。我可以选择一个随机单词,但是一些单词在单词之后有额外的空格,例如缩进。我该如何删除?

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()
python python-3.x
4个回答
2
投票

我想你需要strip()

例:

print(secret_word.strip())

1
投票

使用.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()

1
投票

我认为将rstrip()应用于你的单词应该有效:https://docs.python.org/3/library/stdtypes.html#str.rstrip

所以你可以这样做:secret_word = random.choice(random_word).rstrip()


1
投票

我会对你的代码应用一个rstrip()方法:

secret_word.rstrip()

更多的出轨:https://www.tutorialspoint.com/python/string_rstrip.htm干杯

© www.soinside.com 2019 - 2024. All rights reserved.