Python Join() function can easily convert a list to string
Python provides a magical
join()
method that takes a sequence and converts it to a string.
The list can contain any of the following object types.
- Strings
- Characters
- Numbers.
Python Join() Syntax
string_token.join( iterable ) Parameters: iterable => It could be a list of strings, characters, and numbers string_token => It is also a string such as space'' or comma "," etcetera
The above method joins all the elements present in the iterable separated by the string_token.
python convert list to string
Example 1
listOfMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
we’ll join all the strings in the above list, considering space as a separator
def converttostr(input_seq, seperator): final_str = seperator.join(input_seq) return final_str # List of month names listOfMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] # List of month names separated with a space seperator = ' ' print("OutPut1: ", converttostr(listOfmonths, seperator)) # List of month names separated with a comma seperator = ', ' print("OutPut2: ", converttostr(listOfmonths, seperator))
The output is as follows:
OutPut1: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec OutPut2: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
list of chars into a string
Example 2
- We can also convert a list of characters to a string.
chars = ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"] final = "".join(chars) print(chars) print(final)
The output is as follows:
# helloworld # ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']