如何在不添加末尾空格的情况下用空格连接字符串?

-2 投票
1 回答
9054 浏览
提问于 2025-04-18 18:01

我需要写一段代码,来计算一个句子中特定字母的数量,并且打印出包含这个字母的单词。不过,我不想在结果的最后有空格。目前我的代码是:

a = input("Letter: ")
b = input("Input: ")
a=a.lower()
b=b.lower()
c=b.count(a)
print(c)
words = b.split()
for word in words:
    if a in word:
        print(word, end=' ')

这段代码的输出是:

Letter: e
Input: The quick brown fox jumps over the lazy dog.
3
the over the 

但是在“the”后面有一个空格。你能建议一个去掉这个空格的代码吗?

谢谢

1 个回答

4

你可以在这里使用 join,这样就不会在最后一个单词后面多出空格。把你的 for 循环改写成

' '.join([word for word in words if a in word])

编辑

你的代码应该是

a = input("Letter: ") 
b = input("Input: ") 
a=a.lower() 
b=b.lower() 
c=b.count(a) 
print(c) 
words = b.split() 
print ' '.join([word for word in words if a in word])

撰写回答