2017-05-04 73 views
2

我開始學習python,並得到了這麼多的代碼以允許用戶輸入一系列文本行來輸出最長的行數。你能否告訴我需要添加什麼來顯示最長的文本本身和字符數? 謝謝。用字符數打印系列文本中最長的一行

print('Please enter lines of text.') 
print('Finish with a blank line.') 
maxi = 0 
text = '.' 
while len(text) > 0: 
    text = input() 
    if len(text) > maxi: 
     maxi = len(text) 
if maxi == 0: 
    print('No text entered.') 
else: 
    print('The longest line of text was ' + str(maxi) + ' characters long.') 

回答

1

你要保存的最大長度的文字是這樣的:

print('Please enter lines of text.') 
print('Finish with a blank line.') 
maxi = 0 
maxiText = '' 
text = '.' 
while len(text) > 0: 
    text = input() 
    if len(text) > maxi: 
     maxi = len(text) 
     maxiText = text 
if maxi == 0: 
    print('No text entered.') 
else: 
    print('The longest line of text was ' + str(maxi) + ' characters long. The text is ' + maxiText) 
0

當他高於以前的maxText時,您必須保存測試。 最後你可以打印它。

1

您可以通過做其引入另一個變量來存儲發現的最長行的文本,或替換maxi變量,長度該行的文本並使用len(maxi)來比較長度。雖然這個選擇在這個範圍內可能看起來並不相關,但您可以在將來重新計算的函數比len()更復雜時考慮更大規模的問題。

新變量:

這通過存儲在一個單獨的變量的當前最長行的長度節省處理的一點點。但是,您必須手動將它們保持同步。

print('Please enter lines of text.') 
print('Finish with a blank line.') 
maxi = 0 
text = '.' 
maxline = "" 
while len(text) > 0: 
    text = input() 
    if len(text) > maxi: 
     maxi = len(text) 
     maxline = text 
if maxi == 0: 
    print('No text entered.') 
else: 
    print('The longest line of text was ' + str(maxi) + ' characters long.') 
    print(maxline) 

只有存儲最長行的文本:

這樣,你總是要重新計算最長行的當前長度,但你一定要始終得到正確的長度。

print('Please enter lines of text.') 
print('Finish with a blank line.') 
maxi = "" 
text = '.' 
while len(text) > 0: 
    text = input() 
    if len(text) > len(maxi): 
     maxi = text 
if maxi == "": 
    print('No text entered.') 
else: 
    print('The longest line of text was ' + str(len(maxi)) + ' characters long.') 
    print(maxi)