我正在嘗試實作列印,它輸出最長的行和與之相關的單詞。
with open("alice.txt") as file:
for line in file:
words = line.split()
words_count = len(words)
if maxlines == 0 or len(words) > len(maxlines.split()):
maxlines = line
sentences.append(line)
...
maxlines_len = str((len(maxlines.split())))
print("Longest line has " maxlines_len " words: " maxlines)
如果我在沒有 str() 的情況下宣告它的值,該變數將吐出一個 typeError。有沒有沒有 fstrings 或 str() 的解決方法?
謝謝!
愛麗絲.txt
uj5u.com熱心網友回復:
好吧,你不能對字串和整數求和,但很print()樂意接受任意數量的引數并在內部對它們進行字串化(默認情況下用空格分隔它們;你可以用sep=關鍵字引數控制它):
print("Longest line has", maxlines_len, "words:", maxlines)
如果使用 f-string 格式是一個選項(不知道你為什么不使用它們):
print(f"Longest line has {maxlines_len} words: {maxlines}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485517.html
標籤:Python python-3.x
下一篇:創建一個由可變字串組成的元組
