Answers:
否。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)
我已经做了一个非常有用的方法,可以在Python中的某个位置添加字符串:
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!
s[:-4]