I am new to python and i want to append a smaller string to a bigger string at a position defined by me. For example, have a string aaccddee. Now i want to append string bb to it at a position which would make it aabbccddee. How can I do it? Thanks in advance!
-
stackoverflow.com/questions/4022827/… This should help explain.Coding Orange– Coding Orange2014-12-20 04:54:55 +00:00Commented Dec 20, 2014 at 4:54
5 Answers
You can slice strings up as if they were lists, like this:
firststring = "aaccddee"
secondstring = "bb"
combinedstring = firststring[:2] + secondstring + firststring[2:]
print(combinedstring)
There is excellent documentation on the interwebs.
Comments
There are various ways to do this, but it's a tiny bit fiddlier than some other languages, as strings in python are immutable. This is quite an easy one to follow
First up, find out where in the string c starts at:
add_at = my_string.find("c")
Then, split the string there, and add your new part in
new_string = my_string[0:add_at] + "bb" + my_string[add_at:]
That takes the string up to the split point, then appends the new snippet, then the remainder of the string
Comments
try these in a python shell:
string = "aaccddee"
string_to_append = "bb"
new_string = string[:2] + string_to_append + string[2:]
you can also use a more printf style like this:
string = "aaccddee"
string_to_append = "bb"
new_string = "%s%s%s" % ( string[:2], string_to_append, string[2:] )