【发布时间】:2011-03-08 21:13:11
【问题描述】:
我目前有一个字符串,我想通过在每个字符之间添加空格来编辑它,所以我目前有s = 'abcdefg',我希望它变成s = 'a b c d e f g'。有没有简单的方法可以使用循环来做到这一点?
【问题讨论】:
标签: python string python-3.x
我目前有一个字符串,我想通过在每个字符之间添加空格来编辑它,所以我目前有s = 'abcdefg',我希望它变成s = 'a b c d e f g'。有没有简单的方法可以使用循环来做到这一点?
【问题讨论】:
标签: python string python-3.x
>>> ' '.join('abcdefg')
'a b c d e f g'
【讨论】:
Avoid extraneous whitespace in the following situations: - Immediately inside parentheses, brackets or braces. Yes: spam(ham[1], {eggs: 2}) No: spam( ham[ 1 ], { eggs: 2 } )
您确实指定了“使用循环”
Python 中的字符串是可迭代的,这意味着您可以对其进行循环。
使用循环:
>>> s = 'abcdefg'
>>> s2=''
>>> for c in s:
... s2+=c+' '
>>> s2
'a b c d e f g ' #note the trailing space there...
使用推导式,您可以生成一个列表:
>>> [e+' ' for e in s]
['a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g '] #note the undesired trailing space...
你可以使用map:
>>> import operator
>>> map(operator.concat,s,' '*len(s))
['a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g ']
然后你有那个讨厌的列表而不是一个字符串和一个尾随空格......
你可以使用正则表达式:
>>> import re
>>> re.sub(r'(.)',r'\1 ',s)
'a b c d e f g '
您甚至可以使用正则表达式修复尾随空格:
>>> re.sub(r'(.(?!$))',r'\1 ',s)
'a b c d e f g'
如果你有一个列表,使用join 产生一个字符串:
>>> ''.join([e+' ' for e in s])
'a b c d e f g '
您可以使用string.rstrip() 字符串方法来删除不需要的尾随空格:
>>> ''.join([e+' ' for e in s]).rstrip()
'a b c d e f g'
您甚至可以写入内存缓冲区并获取字符串:
>>> from cStringIO import StringIO
>>> fp=StringIO()
>>> for c in s:
... st=c+' '
... fp.write(st)
...
>>> fp.getvalue().rstrip()
'a b c d e f g'
但由于join 可用于列表或可迭代对象,您不妨在字符串上使用连接:
>>> ' '.join('abcdefg')
'a b c d e f g' # no trailing space, simple!
以这种方式使用join是最重要的Python习语之一。
使用它。
还有性能方面的考虑。阅读this comparison,了解 Python 中的各种字符串连接方法。
【讨论】:
使用 f 字符串,
s = 'abcdefg'
temp = ""
for i in s:
temp += f'{i} '
s = temp
print(s)
a b c d e f g
[Program finished]
【讨论】: