在Python中是否有任何函数可以用来在字符串的特定位置插入值?
就像这样:
“3655879ACB6”,然后在位置4添加“-”,变成“3655-879ACB6”
在Python中是否有任何函数可以用来在字符串的特定位置插入值?
就像这样:
“3655879ACB6”,然后在位置4添加“-”,变成“3655-879ACB6”
当前回答
由于字符串是不可变的,另一种方法是将字符串转换为列表,然后可以在没有任何切片技巧的情况下对其进行索引和修改。但是,要将列表还原为字符串,必须使用空字符串的.join()。
>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'
我不确定这与性能相比如何,但我确实觉得它比其他解决方案更容易看到眼睛。: -)
其他回答
我做了一个非常有用的方法来在Python中的特定位置添加字符串:
def insertChar(mystring, position, chartoinsert ):
mystring = mystring[:position] + chartoinsert + mystring[position:]
return mystring
例如:
a = "Jorgesys was here!"
def insertChar(mystring, position, chartoinsert ):
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!
简单的函数来完成这个:
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'
由于字符串是不可变的,另一种方法是将字符串转换为列表,然后可以在没有任何切片技巧的情况下对其进行索引和修改。但是,要将列表还原为字符串,必须使用空字符串的.join()。
>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'
我不确定这与性能相比如何,但我确实觉得它比其他解决方案更容易看到眼睛。: -)
我想添加另一个简单的一行程序解决方案;)
“-”。加入([_string [4], _string [4:]]