Tuesday 21 September 2021

Python: Convert list of characters to a string

Approach 1: Iterate over list of characters and append every character to the string.

 

convert_list_chars_to_string_1.py

def convert_list_to_string(my_list):
    str = ''

    for ch in my_list:
        str += ch
    
    return str

my_list = ['H', 'e', 'l', 'l', 'o']
my_str = convert_list_to_string(my_list)

print('my_list -> ', my_list)
print('my_str -> ', my_str)

 

Output

my_list ->  ['H', 'e', 'l', 'l', 'o']
my_str ->  Hello

Approach 2: Using join() method of string

join method takes a sequence of strings as argument and join it with this string.

 

convert_list_chars_to_string_2.py

def convert_list_to_string(my_list):
    return ''.join(my_list)

my_list = ['H', 'e', 'l', 'l', 'o']
my_str = convert_list_to_string(my_list)

print('my_list -> ', my_list)
print('my_str -> ', my_str)


Output

my_list ->  ['H', 'e', 'l', 'l', 'o']
my_str ->  Hello


Approach 3: Using reduce method

 

convert_list_chars_to_string_3.py

from operator import concat
from functools import reduce

def convert_list_to_string(my_list):
    return reduce(concat, my_list)

my_list = ['H', 'e', 'l', 'l', 'o']
my_str = convert_list_to_string(my_list)

print('my_list -> ', my_list)
print('my_str -> ', my_str)


Output

my_list ->  ['H', 'e', 'l', 'l', 'o']
my_str ->  Hello






 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment