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


No comments:

Post a Comment

How to connect to VPS with Private Key on Mac OS

1. Use the cd command to navigate to the directory where your private key file is stored. For example, if your private key is in the Downlo...