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!

1

5 Answers 5

2

String is immutable, you might need to do this:

strA = 'aaccddee'
strB = 'bb'
pos = 2
strC = strA[:pos]+strB+strA[pos:]  #  get aabbccddee  
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

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:] )

2 Comments

sorry i did not mark the answer down...i do not even have permission to upvote or downvote...!
Thanks for the honesty @hnvasa. I feel like it was one of the other answerers, but have no real idea.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.