我正在嘗試撰寫一個程式,允許用戶繼續輸入字串,直到輸入一個空字串。然后程式對字串進行排序并按依賴順序(按字典順序)列印字串。
字串輸出應如下所示。
enter a string: the tree is nice and brown
output: tree the nice is brown and
我試圖為自己實作這段代碼,但是我遇到了一個問題,它會多次列印代碼。見下面的代碼。
Enter string: the tree is nice and brown
Output: tree Output: the Output: nice Output: is Output: brown Output: and Enter string:
如何修復我的代碼以洗掉輸出:在字串中的每個單詞之后繼續列印。并且還使最終輸入的新字串列印在新行上。請參閱下面我的最終代碼。
s=input("Enter string: ")
while s!="":
a=s.lower()
b=a.split()
b.sort(reverse=True)
for i in b:
answer=""
answer =i
print("Output: ", answer, end=" ")
s=input("Enter string: ")
uj5u.com熱心網友回復:
while s := input('Enter string: '):
a=s.lower()
b=a.split()
b.sort(reverse=True)
output = ("OUTPUT: \n" " ".join(b)
print(output)
uj5u.com熱心網友回復:
你可以把它分解成兩行。不一定很有啟發性,但只是為了好玩:
while s := input('Enter string: '):
print('Output:\n' ' '.join(sorted(s.lower().split(), reverse=True)))
uj5u.com熱心網友回復:
您可能應該首先收集所有資料,然后對所述資料執行所需的操作。
對您的代碼留下了一些評論:
s=input("Enter string: ")
while s!="":
a=s.lower()
b=a.split()
b.sort(reverse=True)
for i in b: #Every time you input something new you also enter this for-loop
answer="" #This resets the variable every for-loop
answer =i #This tries to concatenate a string i to the variable answer but since you reset the variable every loop you will never get anything else than i here
print("Output: ", answer, end=" ") #Does this run?
s=input("Enter string: ")
“正確”代碼:
s=input("Enter string: ")
while s!="":
# All the input data is split and all characters made lowercase and appended to wordlist variable
a=s.lower()
b=a.split()
wordlist=[]
for i in b:
wordlist.append(i)
# After splitting and making all characters lowercase sort the new list.
wordlist.sort(reverse=True)
# Concatenate the list into a new string
answer=""
for i in wordlist:
answer =" " i
#Print
print("Output:" answer "\n")
s=input("Enter string: ")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464515.html
標籤:Python python-3.x
下一篇:從.xml檔案中提取熊貓資料框
