我知道在Python中可以使用数组表示法对字符串进行切片:str[1:6]
,但是如何对其进行拼接呢?也就是说,用另一个字符串(可能长度不同)替换str[1:6]
?
在Python中,字符串是不可变的。你能做的最好的事情就是构建一个新的字符串:
t = s[:1] + "whatever" + s[6:]
由于Python中的字符串是不可变的,所以你不能这样做。
请尝试下一个方法:
new_s = ''.join((s[:1], new, s[6:]))
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'
Python字符串是不可变的,您需要手动进行以下操作:
new = str[:1] + new + str[6:]
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...
如果需要更符合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]
"".join()
比+
慢。 - Sven Marnach