[英]Looping and Lists - Grok Learning
我今天剛開始在 Grok Learning 上學習編寫 Python 代碼,我目前被困在這個問題上。 我必須創建一個讀取消息的代碼,並且:
我做對了所有事情,但最后我無法擺脫一個空間。 我想知道是否有人知道如何刪除它。 這是我的代碼:
code = []
translation = []
msg = input("code: ")
code = msg.split()
code.reverse()
for c in code:
if c[0].isupper():
translation.append(c)
print("says: ", end='')
for c in translation:
c = c.lower()
print(c, end = ' ')
謝謝:)
您需要對translation
中的所有字母進行迭代,但最后一個字母並在沒有空格的情況下單獨打印:
for c in translation[:-1]:
c = c.lower()
print(c, end = ' ')
print(translation[-1], end='')
這是一個常見的問題:
如果你真的想構建生成的字符串,我會說 pythonic 的方法是str.join()
。 它接受任何可迭代的字符串,例如一個列表,並使用調用它的字符串作為分隔符將所有元素連接在一起。 舉個例子:
my_list = ["1", "2", "3"]
joined = ", ".join(my_list)
# joined == "1, 2, 3"
在你的情況下,你可以做
msg = "Hello hello test Test asd adsa Das"
code = msg.split()
code.reverse()
translation = [c.lower() for c in code if c[0].isupper()]
print("says: ", end='')
print(" ".join(translation))
# output:
# says: das test hello
對於打印,請注意print
也可以采用多個元素並使用分隔符打印它們。 所以,你可以使用這個:
print(*translation, sep=" ")
您也可以省略顯式設置 sep 因為空格是默認設置:
print(*translation)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.