DEV Community

Cover image for python merge string
Python64
Python64

Posted on

python merge string

In Python you can use variables. A variable lets you store some data in your program. A most basic variable would be

>>> a = 1
>>> b = 2

Variables can have types, the type above is a whole number (integer). One of the other variable types is the string, these contain character data. Either a character, a word or a phrase.

>>> s = "Hello"

If you want to merge strings, at first thought, of course, you can use + or + = connecting two strings

>>> a = 'a'
>>> b = 'b'
>>> c = a + b
>>> c
'ab'
>>>

If the entire program requires only two strings, that is no problem

However, if there exist a large number of strings, or even you need to loop stitching, this time there will be a performance problem

Therefore, I recommend using the .join method. If it is not the beginning of some string in place, you can use the temporary list, then join

E.g:

>>> a = 'a'
>>> b = 'b'
>>> c = a.join(b)
>>> c
'b'
>>>

To join two strings:

>>> x = " ".join((a,b))
>>> x
'a b'
>>> 

To have no space use

>>> x = "".join((a,b))
>>> x
'ab'
>>> 

Top comments (0)