如何输出一个没有空格的句子或短语?



这是一个赋值,我们必须接受一个句子或短语作为输入,并输出不带空格的短语。

示例:如果输入是'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))
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))

差不多了。你只需要将列表连接成一个字符串。

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(' ', '')
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