Add string in a certain position in Python

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

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"

回答1:

No. Python Strings are immutable.

>>> s='355879ACB6' >>> s[4:4] = '-' Traceback (most recent call last):   File "", line 1, in  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' 


回答2:

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) 


回答3:

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



回答4:

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:

Simple function to accomplish this:

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


回答6:

If you want many inserts

from rope.base.codeanalyze import ChangeCollector  c = ChangeCollector(code) c.add_change(5, 5, '') c.add_change(10, 10, '') rend_code = c.get_changed() 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!