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
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 : MyList = ['M','y','P','y','t','h','o','n'] In : MyList Out: ['M', 'y', 'P', 'y', 't', 'h', 'o', 'n']
Converting as a single string
In : MyString = ''.join(MyList) In : MyString Out: '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 : MyString = '-'.join(MyList) In : MyString Out: '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 : MyIntList = [1,2,3,4,5] In : MyIntList Out: [1, 2, 3, 4, 5]
In : MyString = ''.join(str(x) for x in MyIntList) In : MyString Out: '12345'