[英]Adding characters to a string in python 3
我目前有一個字符串,我想通過在每個字符之間添加空格來進行編輯,所以我目前有s = 'abcdefg'
並且我希望它成為s = 'abcdef 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!
以這種方式使用join
是最重要的 Python 習語之一。
用它。
還有性能方面的考慮。 閱讀有關 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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.