Wednesday 24 January 2024

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()

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))

No comments:

Post a Comment

How to cycle a fish tank right way

  Here is the fishless cycle. You are adding WAY too much ammonia, and stopping (or greatly slowing) the growth of the very bacteria you wan...