Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (47.6k points)

I want an efficient way to append one string to another in Python.

var1 = "foo"

var2 = "bar"

var3 = var1 + var2

Is there any good built-in method to use?

2 Answers

0 votes
by (106k points)

CPython provides a special case, but for that, you should have one reference to a string and you concatenate another string to the end, now special cases this and tries to extend the string in place.

And one advantage of using this is you can get the solution in O(n) time complexity.

e.g.

s = "" for i in range(n):

s+=str(i)

Another thing you can use the .join() function to concatenate the string below is the code for that:-

l=[]

l.append(‘foo’)

l.append(‘bar’)

l.append(‘baz’)

s=’ ‘.join(l)

print(s)

image

0 votes
by (20.3k points)

Try doing this:

str1 = "Hello"

str2 = "World"

newstr = " ".join((str1, str2))

Here, str1 and str2 will be joined with space as separators. You can also try doing "".join(str1, str2, ...). str.join() takes an iterable, so you'd have to put the strings in a list or a tuple.

That's about as efficient as it gets for a builtin method.

Related questions

0 votes
1 answer
+3 votes
2 answers
0 votes
1 answer
asked Jul 22, 2019 in Python by Eresh Kumar (45.3k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...