在Python中的特定位置添加字符串


157

Python中是否可以使用任何函数在字符串的某个位置插入值?

像这样:

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

Answers:


272

否。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'

9
除此之外,您可以使用负索引从右侧获得位置,例如s[:-4]
Reuben L.

使用较新的格式字符串:'{0}-{1}'。format(s [:4],s [4:])
2013年

60

这看起来非常简单:

>>> 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)

26

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

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

我不确定这与性能相比如何,但是我确实觉得它比其他解决方案容易。;-)


7

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

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

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!

8
为什么要计算字符串tho的长度?
Yytsi'8

2
也许他想检查索引是否小于字符串的长度...然后忘记了。
sce

Python通常使用下划线区分大小写来表示函数名称,而不是驼峰式区分。
迈克尔·贝茨

2

我认为上述答案很好,但我会解释说,它们有一些意想不到但很好的副作用...

def insert(string_s, insert_s, pos_i=0):
    return string_s[:pos_i] + insert_s + string_s[pos_i:]

如果索引pos_i很小(太负),则将插入字符串。如果太长,则会附加插入字符串。如果pos_i在-len(string_s)和+ len(string_s)-1之间,则将插入字符串插入正确的位置。


0

使用f-string的Python 3.6+:

mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"

'1362511338_314'

-3

如果您想插入很多

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()

我不清楚您要导入的库来自哪里,或者输出是什么。
基督
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.