我目前有一个字符串,想通过在每个字符之间添加空格来编辑它,所以我目前有s = 'abcdefg'
,我希望它变成s = 'a b c d e f g'
。是否有一种简单的方法可以使用循环来实现这一点?
我目前有一个字符串,想通过在每个字符之间添加空格来编辑它,所以我目前有s = 'abcdefg'
,我希望它变成s = 'a b c d e f g'
。是否有一种简单的方法可以使用循环来实现这一点?
>>> ' '.join('abcdefg')
'a b c d e f g'
你提到了“使用循环”。
在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:
>>> ' '.join('abcdefg')
'a b c d e f g' # no trailing space, simple!
在Python中,使用join
的方式是最重要的编程习惯之一。
请使用它。s = 'abcdefg'
temp = ""
for i in s:
temp += f'{i} '
s = temp
print(s)
a b c d e f g
[Program finished]