如何在特定位置插入字符串?

259 投票
9 回答
570319 浏览
提问于 2025-04-16 13:24

在Python中,有没有什么函数可以让我在字符串的某个位置插入一个值呢?

比如说,我有一个字符串是:

"3655879ACB6",然后我想在第4个位置加上一个"-",这样就变成了"3655-879ACB6"

9 个回答

38

因为字符串是不可改变的,所以另一种方法是把字符串变成一个列表。列表可以直接通过索引来修改,不需要那些复杂的切片技巧。不过,要把列表再变回字符串,你需要用一个空字符串来使用 .join() 方法。

>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'

我不太确定这种方法在性能上如何比较,但我觉得它看起来比其他解决方案更简单易懂。;-)

86

这看起来非常简单:

>>> 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)
427

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

撰写回答