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

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

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

像这样:

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

Is there any function in Python that I can use to insert a value in a certain position of a string?

Something like this:

"3655879ACB6" then in position 4 add "-" to become "3655-879ACB6"


回答 0

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

No. Python Strings are immutable.

>>> s='355879ACB6'
>>> s[4:4] = '-'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

It is, however, possible to create a new string that has the inserted character:

>>> s[:4] + '-' + s[4:]
'3558-79ACB6'

回答 1

这看起来非常简单:

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

This seems very easy:

>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash
3558-79ACB6

However if you like something like a function do as this:

def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

回答 2

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

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

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

As strings are immutable another way to do this would be to turn the string into a list, which can then be indexed and modified without any slicing trickery. However, to get the list back to a string you’d have to use .join() using an empty string.

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

I am not sure how this compares as far as performance, but I do feel it’s easier on the eyes than the other solutions. ;-)


回答 3

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

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

Simple function to accomplish this:

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

回答 4

我已经做了一个非常有用的方法,可以在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!

I have made a very useful method to add a string in a certain position in Python:

def insertChar(mystring, position, chartoinsert ):
    longi = len(mystring)
    mystring   =  mystring[:position] + chartoinsert + mystring[position:] 
    return mystring  

for example:

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, '%'))   

we will have as an output:

-Jorgesys was here!
Jorgesys @was here!
Jorgesys was h%ere!

回答 5

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

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之间,则将插入字符串插入正确的位置。

I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them…

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

If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) – 1, the insert string gets inserted into the correct place.


回答 6

使用f-string的Python 3.6+:

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

'1362511338_314'

Python 3.6+ using f-string:

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

gives

'1362511338_314'

回答 7

如果您想插入很多

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

If you want many inserts

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