Python中是否有任何函数可以用来在字符串的某个位置插入一个值?
像这样的东西:
"3655879ACB6"
然后在位置4添加"-"
成为"3655-879ACB6"
Ign*_*ams 229
不,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
Run Code Online (Sandbox Code Playgroud)
但是,可以创建一个具有插入字符的新字符串:
>>> s[:4] + '-' + s[4:]
'3558-79ACB6'
Run Code Online (Sandbox Code Playgroud)
Mar*_*sar 51
这似乎很容易:
>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash
3558-79ACB6
Run Code Online (Sandbox Code Playgroud)
但是,如果你喜欢像函数这样的东西:
def insert_dash(string, index):
return string[:index] + '-' + string[index:]
print insert_dash("355879ACB6", 5)
Run Code Online (Sandbox Code Playgroud)
jat*_*ism 23
由于字符串是不可变的,另一种方法是将字符串转换为一个列表,然后可以在没有任何切片技巧的情况下对其进行索引和修改.但是,要将列表返回到字符串,您必须使用.join()
空字符串.
>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'
Run Code Online (Sandbox Code Playgroud)
我不确定这与性能相比如何,但我确实觉得它比其他解决方案更容易.;-)
小智 9
Python 3.6+ 使用 f 字符串:
mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"
Run Code Online (Sandbox Code Playgroud)
给出
'1362511338_314'
Run Code Online (Sandbox Code Playgroud)
我做了一个非常有用的方法来在 Python 的某个位置添加一个字符串:
def insertChar(mystring, position, chartoinsert ):
longi = len(mystring)
mystring = mystring[:position] + chartoinsert + mystring[position:]
return mystring
Run Code Online (Sandbox Code Playgroud)
例如:
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, '%'))
Run Code Online (Sandbox Code Playgroud)
我们将有一个输出:
-Jorgesys was here!
Jorgesys @was here!
Jorgesys was h%ere!
Run Code Online (Sandbox Code Playgroud)
简单的功能可以完成此任务:
def insert_str(string, str_to_insert, index):
return string[:index] + str_to_insert + string[index:]
Run Code Online (Sandbox Code Playgroud)