在Python中的某个位置添加字符串

Mic*_*ade 134 python string

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)

  • 除此之外,你可以使用负指数从右边获得一个位置,例如`s [: - 4]` (8认同)
  • 使用较新的格式字符串用语:'{0}-{1}'.format(s[:4], s[4:]) (3认同)

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)

  • 这个的时间复杂度是多少? (2认同)
  • @Embedded_Mugs我相信它是O(n),因为1.子字符串选择是O(k)+O(nk) = O(n),其中k是字符串的第一部分(这里k=4)2.字符串连接是O(k+1) + O(n) = O(n)。字符串连接的复杂度为 O(n),因为字符串是可变的,并且它会为每个连接创建一个新字符串。 (2认同)

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)

  • 也适用于负索引 `f"{mys[:-2]}_{mys[-2:]}"` `'13625113383_14'` (2认同)

Jor*_*sys 5

我做了一个非常有用的方法来在 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)

  • 为什么要计算字符串的长度? (9认同)
  • 也许他想检查索引是否小于字符串的长度......然后忘记了。 (3认同)

vat*_*sug 5

简单的功能可以完成此任务:

def insert_str(string, str_to_insert, index):
    return string[:index] + str_to_insert + string[index:]
Run Code Online (Sandbox Code Playgroud)