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

Mức thuế ở Úc từ 07/2024

Chính phủ Úc đã thay đổi các mức thuế suất cho thu nhập cá nhân và các mức thu nhập (được gọi là ‘ngưỡng’) áp dụng những thuế suất này. Việc...