【问题标题】:How do I remove space at the end of an output in python?如何在 python 的输出末尾删除空格?
【发布时间】:2017-11-15 02:50:05
【问题描述】:

我有一个程序可以计算并打印包含特定字符的句子中的所有单词(忽略大小写)。

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=' ')

该程序按预期工作,但对于打印的最后一个单词,我不想在它后面有空格。

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

【问题讨论】:

  • 拜托,拜托,请复制 (Ctrl-C) 并粘贴 (Ctrl-V) 您的代码并输出到您的问题中。

标签: python python-2.7 python-3.x


【解决方案1】:

为什么不使用list comprehensionstr.join

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

【讨论】:

  • 更好的是,让print 为您加入:print(*[w for w in ip if item in w]) 这使用 splat 来解压列表。
【解决方案2】:

我认为没有办法删除它,因为它是您终端的一部分。我能给你最好的答案。

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

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))

【讨论】:

    【解决方案3】:

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

    # 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
    

    【讨论】:

      【解决方案4】:

      您已经很接近了,只需将您的打印语句从 print((word), end=' ') 更改为 print((word), end='')。您的 print 语句末尾有一个空格,但您不想要空格,所以将结尾设为空字符串。

      【讨论】:

      • 当我更改为... print((word), end='') ...它也会删除句子中的空格。我应该如何编写它,以便它只删除末尾的空格而不是单词之间的空格。
      猜你喜欢
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多