在Python中是否有任何函数可以用来在字符串的特定位置插入值?

就像这样:

“3655879ACB6”,然后在位置4添加“-”,变成“3655-879ACB6”


当前回答

Python 3.6+使用f-string:

mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"

给了

'1362511338_314'

其他回答

如果需要在多个位置插入给定的字符,请始终考虑创建一个子字符串列表,然后使用.join()而不是+进行字符串连接。这是因为,由于Python的str是可变的,+字符串连接总是增加额外的开销。更多信息可以在这里找到。

不。Python字符串是不可变的。

>>> s='355879ACB6'
>>> s[4:4] = '-'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

但是,可以创建一个包含插入字符的新字符串:

>>> s[:4] + '-' + s[4:]
'3558-79ACB6'

这看起来很简单:

>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash
3558-79ACB6

然而,如果你喜欢函数之类的东西,可以这样做:

def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

简单的函数来完成这个:

def insert_str(string, str_to_insert, index):
    return string[:index] + str_to_insert + string[index:]

Python 3.6+使用f-string:

mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"

给了

'1362511338_314'