2017-06-13 176 views
-17

我有一个程序可以计算并打印包含特定字符(忽略大小写)的句子中的所有单词。如何删除python输出结尾的空格?

代码在Python -

item=input() 
ip=input().tolower() 
r=ip.count(item) 
print(r) 
ip=ip.split() 
for word in ip: 
    if item in word: 
     print((word), end=' ') 

这个程序工作正常,但在最后一个字是打印的,我不想以后成为一个空白。 enter image description here

如果有人可以指导我如何删除空间,将不胜感激。

+0

请复制(Ctrl-C)并粘贴(Ctrl-V)您的代码并输出到您的问题中。 – jambrothers

+0

RTFM ['join'](https://docs.python.org/2/library/stdtypes.html?highlight=join#str.join) –

回答

0

我不认为有办法删除它,因为它是你的终端的一部分。最佳答案我可以给你。

虽然我扩展了代码,因为我有点无聊。

sentence = input("Enter a sentence: ").lower() 
pull = input("Which character(s) do you want to count?: ").lower() 
for c in pull: 
    occurrences = 0 
    for character in sentence: 
     if c == character: 
      occurrences+=1 
    if c!=" ": print("\'%s\' appears %d times"%(c, occurrences)) 
    for word in sentence.split(): 
     occurrences = 0 
     for character in word: 
      if c == character: 
       occurrences+=1 
     if occurrences == 1: 
      print(("1 time in \'%s\'")%(word)) 
     elif occurrences > 0: 
      print(("%d times in \'%s\'")%(occurrences,word)) 
0

你接近,只是改变你的打印语句从print((word), end=' ')print((word), end='')。您的打印语句最后有一个空格,但您不需要空格,因此请将结尾设为空字符串。

+0

当我切换到... print((word),end = '')...它也删除句子中的空格。我该如何写它,以便它只消除末尾的空白而不是单词之间的空格。 –

1

为什么不使用list comprehensionstr.join

print(' '.join([w for w in ip if item in w])) 
0

+带有列表理解的解决方案显得更加简洁,但如果您更喜欢替代方案,则可以使用以下方法。它已经过测试并与图片中的示例一起工作。

# Amended solution. The commented lines are the amendment. 
item = input('Letter: ') 
ip = input('Input: ').lower() 
r = ip.count(item) 
print(r) 
ip = ip.split() 
outputString = '' # Added: Initialise an empty string to keep the answer 
for word in ip: 
    if item in word: 
     outputString += word + ' ' # Changed: Accumulates the answer in a string 
print(outputString[:-1]) # Added: Prints all the string's characters 
          # except the last one, which is the additional space