First of all, if one ignores the space-to-empty-string issue, converting a list of characters to a string and back again is as simple as:
# Converting the list to a string:
total_string = ''.join(list_of_characters)
# Converting the string to a list:
list_of_characters = list(total_string)
In your case, you need the extra step of converting between spaces and empty strings, which you can accomplish with a list comprehension.
For instance, here's a list comprehension (split onto multiple lines for extra clarity) that reproduces a list faithfully, except with empty string elements replaced with spaces:
[
' ' if char == '' else char
for char in list_of_characters
]
So your final conversions would look like this:
# Converting the list to a string:
total_string = ''.join([' ' if char == '' else char for char in list_of_characters])
# Converting the string to a list:
list_of_characters = ['' if char == ' ' else char for char in total_string]
Note that one can iterate over a string just like iterating over a list, which is why that final comprehension can simply iterate over total_string
rather than having to do list(total_string)
.
P.S. An empty string (''
) evaluates to False
in boolean contexts, so you could make use of the or
operator's short-circuiting behavior to use this shorter (though arguably less immediately legible) version:
# Converting the list to a string:
total_string = ''.join([char or ' ' for char in list_of_characters])