[英]Python readlines() splits line into two
我正在從文本文件中讀取行。 在文本文件中,每行只有一個單詞。 我可以從文件中讀取並打印單詞,但不是整個單詞都打印在一行上。 這個詞分為兩個部分。 印刷單詞的字母混合在一起。
這是我的代碼:
import random
fruitlist = open('fruits.txt', 'r')
reading_line = fruitlist.readlines()
word = random.choice(reading_line)
mixed_word = ''.join(random.sample(word,len(word)))
print(mixed_word)
fruitlist.close()
如何在一行上顯示一個單詞?
編輯:
這是文本文件的內容:
pinapple
pear
strawberry
cherry
papaya
腳本應打印以下單詞之一(字母混合在一起):
erpa
(這相當於梨)
現在它顯示如下:
erp
a
那是因為您還要改寫行中的readlines
或line迭代器的行終止字符。 使用strip()
擺脫它們(或rstrip()
)
這樣做(避免readlines
順便說一句):
with open('fruits.txt', 'r') as fruitlist:
reading_line = [x.strip() for x in fruitlist]
word = random.choice(reading_line)
mixed_word = ''.join(random.sample(word,len(word)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.