Convert String to List and List to String

Convert String to List

 my_string = "hello world"


method_1 = list(my_string)
method_2 = my_string.split()
print(method_1)
print(method_2)

The result will be:
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
['hello', 'world']

Convert List to String
my_list = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
string_from_list = "".join(my_list)

If your list contains elements other than strings (e.g., numbers), you need to convert them to strings first using the map() function or a list comprehension.

string_from_numbers = ''.join(map(str, my_list_of_numbers))


Post a Comment

0 Comments