Reputation: 860
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!
Upvotes: 3
Views: 387
Reputation: 2122
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:] )
Upvotes: 1
Reputation: 2067
Let say your string object is s=aaccddee
. The you can do it as:
s = s[:2] + 'bb' + s[2:]
Upvotes: 0
Reputation: 1657
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.
Upvotes: 1
Reputation: 6138
String is immutable, you might need to do this:
strA = 'aaccddee'
strB = 'bb'
pos = 2
strC = strA[:pos]+strB+strA[pos:] # get aabbccddee
Upvotes: 2
Reputation: 48326
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
Upvotes: 1