在Python中的某个位置添加string

Python中是否有任何函数可以用来在string的某个位置插入一个值?

像这样的东西:

"3655879ACB6"然后在位置4加"-"变成"3655-879ACB6"

否。Pythonstring是不可变的。

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

但是,可以创build一个具有插入字符的新string:

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

这似乎很简单:

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

但是,如果你喜欢像一个function这样做:

 def insert_dash(string, index): return string[:index] + '-' + string[index:] print insert_dash("355879ACB6", 5) 

由于string是不可变的,另一种方法是将string转换为列表,然后可以对其进行索引和修改,而不需要任何切片技巧。 但是,要将列表返回到string,您必须使用.join()使用空string。

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

我不知道这是如何比较performance,但我觉得这比其他解决scheme更容易。 😉

我已经做了一个非常有用的方法来在Python中的某个位置添加一个string

 def insertChar(mystring, position, chartoinsert ): longi = len(mystring) mystring = mystring[:position] + chartoinsert + mystring[position:] return mystring 

例如:

 a = "Jorgesys was here!" def insertChar(mystring, position, chartoinsert ): longi = len(mystring) mystring = mystring[:position] + chartoinsert + mystring[position:] return mystring #Inserting some characters with a defined position: print(insertChar(a,0, '-')) print(insertChar(a,9, '@')) print(insertChar(a,14, '%')) 

我们将有一个输出:

 -Jorgesys was here! Jorgesys @was here! Jorgesys was h%ere! 

如果你想要多个插入

 from rope.base.codeanalyze import ChangeCollector c = ChangeCollector(code) c.add_change(5, 5, '<span style="background-color:#339999;">') c.add_change(10, 10, '</span>') rend_code = c.get_changed() 

简单的function来完成这一点:

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