3

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!

hnvasa
  • 830
  • 4
  • 13
  • 26
  • http://stackoverflow.com/questions/4022827/how-to-insert-some-string-in-the-given-string-at-given-index-in-python This should help explain. – Coding Orange Dec 20 '14 at 04:54

5 Answers5

2

String is immutable, you might need to do this:

strA = 'aaccddee'
strB = 'bb'
pos = 2
strC = strA[:pos]+strB+strA[pos:]  #  get aabbccddee  
Paul Lo
  • 6,032
  • 6
  • 31
  • 36
1

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

Gagravarr
  • 47,320
  • 10
  • 111
  • 156
1

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.

Tony
  • 1,645
  • 1
  • 10
  • 13
1

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:] )
macguru2000
  • 2,042
  • 2
  • 18
  • 27
0

Let say your string object is s=aaccddee. The you can do it as:

s = s[:2] + 'bb' + s[2:]
Amit Sharma
  • 1,987
  • 2
  • 18
  • 29