Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在读取文件时,如何消除多余的空间_Python_Python 3.x - Fatal编程技术网

Python 在读取文件时,如何消除多余的空间

Python 在读取文件时,如何消除多余的空间,python,python-3.x,Python,Python 3.x,我试图从文件中读取一个单词,然后随机选择一个单词。我可以随机选择一个单词,但是有些单词后面有额外的空格,例如缩进。我如何删除这个 import random random_word = [] secret_word = [] def choose_secret_word(): infile = open("words.txt") for every_item in infile: random_word.append(every_item) se

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

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()

例如:

print(secret_word.strip())
我认为将rstrip()应用于您的word应该可以:

因此,您可以:
secret\u word=random.choice(random\u word).rstrip()

我认为将rstrip()应用于您的word应该有效:

因此,您可以:
secret\u word=random.choice(random\u word).rstrip()
我会对您的代码应用rstrip()方法:

secret_word.rstrip()
这里有更多脱轨: 干杯

我将对您的代码应用rstrip()方法:

secret_word.rstrip()
这里有更多脱轨:
干杯

如果文件中有重复的单词,则获得频率更高的单词的可能性更大。使用集合而不是列表来消除重复。如果文件中有重复的单词,则获得频率更高的单词的几率更大。使用集合而不是列表进行重复数据消除。