How do I add a smaller line between a large line in python?

I am new to python and I want to add a smaller line to a larger line at a position defined by me. For example, enter a string aaccddee

. Now I want to add a line bb

to it at a position that would make it aabbccddee

. How should I do it? Thanks in advance!

+3


source to share


5 answers


You can strip out lines as if they were lists, for example:

firststring = "aaccddee"
secondstring = "bb"
combinedstring = firststring[:2] + secondstring + firststring[2:]
print(combinedstring)

      



There is excellent documentation on interventions .

+1


source


The string is immutable, you may need the following:



strA = 'aaccddee'
strB = 'bb'
pos = 2
strC = strA[:pos]+strB+strA[pos:]  #  get aabbccddee  

      

+2


source


There are various ways to do this, but this is a tiny bit than some other languages ​​since strings in python are immutable. It's pretty easy to follow

First, find out where the line c

starts with:

add_at = my_string.find("c")

      

Then split the line there and add the new part to

new_string = my_string[0:add_at] + "bb" + my_string[add_at:]

      

This translates the line to the split point, then adds a new chunk, then the rest of the line

+1


source


try them in python shell:

string = "aaccddee"
string_to_append = "bb"
new_string = string[:2] + string_to_append + string[2:]

      

you can also use more print style like this:

string = "aaccddee"
string_to_append = "bb"
new_string = "%s%s%s" % ( string[:2], string_to_append, string[2:] )

      

+1


source


Let's say your string object s=aaccddee

. You can do it like:

s = s[:2] + 'bb' + s[2:]

      

0


source







All Articles