如何拼接字符串?

19

我知道在Python中可以使用数组表示法对字符串进行切片:str[1:6],但是如何对其进行拼接呢?也就是说,用另一个字符串(可能长度不同)替换str[1:6]

6个回答

26

在Python中,字符串是不可变的。你能做的最好的事情就是构建一个新的字符串:

t = s[:1] + "whatever" + s[6:]

15

由于Python中的字符串是不可变的,所以你不能这样做。

请尝试下一个方法:

new_s = ''.join((s[:1], new, s[6:]))

我完全可以返回一个新的字符串。 - mpen
我们正在连接3个字符串...性能差异可以忽略不计。虽然有时我也倾向于使用超过2个字符串的方式。 - mpen
2
仅对于三个字符串,如果您的字符串长度小于几KB,则"".join()+慢。 - Sven Marnach

7
没关系。我以为可能有内置函数。我写了下面的代码代替它:
def splice(a,b,c,d=None):
    if isinstance(b,(list,tuple)):
        return a[:b[0]]+c+a[b[1]:]
    return a[:b]+d+a[c:]

>>> splice('hello world',0,5,'pizza')
'pizza world'

>>> splice('hello world',(0,5),'pizza')
'pizza world'

4

Python字符串是不可变的,您需要手动进行以下操作:

new = str[:1] + new + str[6:]

3

What about such try?

>>> str = 'This is something...'
>>> s = 'Theese are'
>>> print str
This is something...
>>> str = str.replace(str[0:7], s)
>>> print str
Theese are something...

1
不行。如果子字符串出现了多次,这种方法就会失败。而且,你正在切片字符串并搜索一个已知位置的字符串时(不太优化)。 - mpen

0

如果需要更符合JavaScript标准的字符串剪辑:

def splice(target, start, delete_count='', insert=''):
    """
    >>> splice('hello pizza world', 6, 5, 'pasta')
    ('hello pasta world', 'pizza')

    >>> s = 'hello pizza world'
    >>> s, food = splice(s, (6, 5), 'pasta')
    >>> s, food
    ('hello pasta world', 'pizza')
    """
    if isinstance(start, (list, tuple)):
        insert = delete_count
        start, delete_count = start
    delete_count += start
    return target[:start] + insert + target[delete_count:], target[start:delete_count]

请注意,因为在Python中字符串参数是不可变的,所以必须返回两个参数:修改后的字符串和已删除的文本。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接