简体   繁体   English

在python 3中向字符串添加字符

[英]Adding characters to a string in python 3

I currently have a string that I want to edit by adding spaces between each character, so I currently have s = 'abcdefg' and I want it to become s = 'abcdef g' .我目前有一个字符串,我想通过在每个字符之间添加空格来进行编辑,所以我目前有s = 'abcdefg'并且我希望它成为s = 'abcdef g' Is there any easy way to do this using loops?有没有什么简单的方法可以使用循环来做到这一点?

>>> ' '.join('abcdefg')
'a b c d e f g'

You did specify "using loops"您确实指定了“使用循环”

A string in Python is an iterable, meaning you can loop over it. Python 中的字符串是可迭代的,这意味着您可以遍历它。

Using loops:使用循环:

>>> s = 'abcdefg'
>>> s2=''
>>> for c in s:
...    s2+=c+' '
>>> s2
'a b c d e f g '    #note the trailing space there...

Using a comprehension, you can produce a list:使用理解,您可以生成一个列表:

>>> [e+' ' for e in s]
['a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g ']  #note the undesired trailing space...

You can use map :您可以使用map

>>> import operator
>>> map(operator.concat,s,' '*len(s))
['a ', 'b ', 'c ', 'd ', 'e ', 'f ', 'g ']

Then you have that pesky list instead of a string and a trailing space...然后你有那个讨厌的列表而不是一个字符串和一个尾随空格......

You could use a regex:您可以使用正则表达式:

>>> import re
>>> re.sub(r'(.)',r'\1 ',s)
'a b c d e f g '

You can even fix the trailing space with a regex:您甚至可以使用正则表达式修复尾随空格:

>>> re.sub(r'(.(?!$))',r'\1 ',s)
'a b c d e f g'

If you have a list, use join to produce a string:如果您有一个列表,请使用join生成一个字符串:

>>> ''.join([e+' ' for e in s])
'a b c d e f g '

You can use the string.rstrip() string method to remove the unwanted trailing whitespace:您可以使用string.rstrip()字符串方法删除不需要的尾随空格:

>>> ''.join([e+' ' for e in s]).rstrip()
'a b c d e f g'

You can even write to a memory buffer and get a string:您甚至可以写入内存缓冲区并获取字符串:

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

But since join works on lists or iterables, you might as well use join on the string:但由于join适用于列表或可迭代对象,您不妨在字符串上使用 join:

>>> ' '.join('abcdefg')
'a b c d e f g'   # no trailing space, simple!

The use of join in this way is one of the most important Python idioms.以这种方式使用join是最重要的 Python 习语之一。

Use it.用它。

There are performance considerations as well.还有性能方面的考虑。 Read this comparison on various string concatenation methods in Python.阅读有关 Python 中各种字符串连接方法的比较

Using f-string,使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM