我正在尝试从文件中读取一个单词,然后随机选择一个单词。我可以选择一个随机单词,但是某些单词在单词之后有多余的空格,例如缩进。我该如何删除?
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()
答案 0 :(得分:2)
我认为您需要strip()
示例:
print(secret_word.strip())
答案 1 :(得分: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()
答案 2 :(得分:1)
我认为将rstrip()应用于您的单词应该可以:https://docs.python.org/3/library/stdtypes.html#str.rstrip
因此您可以执行以下操作:
secret_word = random.choice(random_word).rstrip()
答案 3 :(得分:1)
我将对您的代码应用rstrip()方法:
upstream app-name-production-backend {
server unix:///home/rails/apps/app-name/production/shared/sockets/puma.sock;
}
server {
listen 80;
listen [::]:80 ipv6only=on;
root /home/rails/apps/app-name/production/current/public/;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
if (!-f $request_filename) {
proxy_pass http://app-name-production-backend;
break;
}
}
}
更多出轨在这里:https://www.tutorialspoint.com/python/string_rstrip.htm 欢呼声