从列表中的最后一项删除空格

时间:2014-08-19 00:21:54

标签: python

如何从此代码中仅删除最后一个空格?当我省略打印中的end=" "时,它会删除所有空格,我不希望这样。

r = input("Line: ")
while True:
    n = r.split()
    if r == "":
      break  
    else:
      for word in n:
        print(word[::-1], end=" ")
      r = input("\nLine: ")

如果没有end=" ",当我输入"hello world"时,会输出"ollehdlrow"。当我添加end=" "时,它还会打印一个额外的空格,如下所示:"olleh dlrow "

我如何获得这个:"olleh dlrow"

3 个答案:

答案 0 :(得分:2)

在列表值之间插入字符的正确方法是使用str.join

print(' '.join(word[::-1] for word in n))

实施例

>>> n = ['hello', 'world']
>>> ' '.join(word[::-1] for word in n)
'olleh dlrow'

代码改进

您的代码可以这样写:

while True:
    line = input("Line: ")
    if not line:
        break
    print(' '.join(word[::-1] for word in line.split()))

答案 1 :(得分:0)

这是split()函数的特定行为。因此,为了做你想做的事,你想要分开' '。请参阅以下代码段之间的区别:

In [10]: 'this is a    test'.split()
Out[10]: ['this', 'is', 'a', 'test']

In [11]: 'this is a    test'.split(' ')
Out[11]: ['this', 'is', 'a', '', '', '', 'test']

要删除结束空格,您需要使用rstrip()函数。所以你应该这样做:

In [12]: 'this is a    test    '.rstrip(' ').split(' ')
Out[12]: ['this', 'is', 'a', '', '', '', 'test']

答案 2 :(得分:0)

正则表达式解决方案:

>>> import re
>>> s='Hello there big     fella!'
>>> re.sub(r'([^\s]+)', lambda x: x.group(1)[::-1], s)
'olleH ereht gib     !allef'
相关问题