How to convert a list to string in python?

Sometimes, we need a combined string like output or return from our Python code. Is it possible to obtain a combined string like output from a list? Sure, everything is possible in Python. The only thing you have to do is, just Love Python!!

Please go through the startup sessions of Python and get a basic idea on how to code Python. Now-a-days we do not have enough time to waste. We all are busy! And we required some automation tools to reduce the work load and save the time. Python is a good and simple language for this purpose. Bookmark the Index page and read more about Python.

This is a simple, but tricky code shortcut to convert a Python List to a String. This can be done by the help of Python method join(). The method join() returns a string in which the string elements of sequence have been joined by ‘str‘ separator.

Syntax of Join Method

str.join(list)

Example

print('-'.join(["C","R","Y","B","I","T"]))

Output

C-R-Y-B-I-T

Yup, now we are going with a practical example.

Converting a list with string contents to a single string.

List in question is ‘MyList‘ with elements [‘M’,’y’,’P’,’y’,’t’,’h’,’o’,’n’] and we are going to join them as a single string with value “MyPython.”

In [34]: MyList = ['M','y','P','y','t','h','o','n']

In [35]: MyList
Out[35]: ['M', 'y', 'P', 'y', 't', 'h', 'o', 'n']

Converting as a single string

In [36]: MyString = ''.join(MyList)

In [37]: MyString
Out[37]: 'MyPython'

Wow, that’s it!!
You can also use any separators for join method. For example, if you want to join the list with a separator “-” use the following syntax:

In [38]: MyString = '-'.join(MyList)

In [39]: MyString
Out[39]: 'M-y-P-y-t-h-o-n'

Yeah, you got the idea!!

Joining integer lists to a string

To join a list which has integer items, you can use the following syntax.

In [42]: MyIntList = [1,2,3,4,5]

In [43]: MyIntList
Out[43]: [1, 2, 3, 4, 5]

Joining

In [47]: MyString = ''.join(str(x) for x in MyIntList)

In [48]: MyString
Out[48]: '12345'

That’s it!

What is isinstance function in Python?

Arunlal Ashok

Sr. Linux Server Administrator. I'm managing Linux servers since 2012. I started this blog to share and discuss my ideas. Check My Profile in uPwork (oDesk) and create a job, if you need any administration help. Thanks!!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *