這是一項作業,我們必須將一個句子或短語作為輸入并輸出沒有空格的短語。
示例:如果輸入是 'hello there' 輸出將是 'hellothere'
到目前為止,我的代碼僅以單獨的字母輸出字串:如“h”、“e”、“l”等
def output_without_whitespace(input_str):
lst = []
for char in input_str:
if char != ' ':
lst.append(char)
return lst
if __name__ == '__main__':
phrase = str(input('Enter a sentence or phrase:\n'))
print(output_without_whitespace(phrase))
uj5u.com熱心網友回復:
def output_without_whitespace(input_str):
str1=input_str.replace(" ","")
return str1
if __name__ == '__main__':
phrase = str(input('Enter a sentence or phrase:\n'))
print(output_without_whitespace(phrase))
uj5u.com熱心網友回復:
你已經差不多了。您只需要將串列加入一個字串。
print(''.join(output_without_whitespace(phrase)))
您可以用串列理解替換函式中的回圈。
def output_without_whitespace(input_str):
return [ch for ch in input_str if ch != ' ']
這將回傳與您的實作相同的串列。
如果您希望您的函式回傳一個字串,我們可以使用join之前的相同內容:
def output_without_whitespace(input_str):
return ' '.join([ch for ch in input_str if ch != ' '])
但是如果我們這樣做,我們真的不需要將串列傳遞給join. 相反,我們可以使用生成器運算式。
def output_without_whitespace(input_str):
return ' '.join(ch for ch in input_str if ch != ' ')
正如其他人指出的那樣,如果我們只使用replace.
def output_without_whitespace(input_str):
return input_str.replace(' ', '')
uj5u.com熱心網友回復:
def output_without_whitespace(phrase):
return phrase.replace(" ", "")
if __name__ == '__main__':
phrase = str(input('Enter a sentence or phrase:\n'))
print(output_without_whitespace(phrase))
參考:https : //stackoverflow.com/a/8270146/17190006
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326427.html
