Home > Back-end >  How do I make a list equal to string or vice versa
How do I make a list equal to string or vice versa

Time:05-20


typed_words = ['T', "y", "p", "e", "", "t", "h", "i", "s"]  
target_text = "Type this"

I've tried using the join method but since there is a empty element in the list it creates a string with no spaces. The goal is to either convert the string to into the list or the list into the string.

CodePudding user response:

For making a list, you need to iterate every char and append it to a list.

def strToList(s):
    l = []

    for c in s:
        l.append(c)
    
    return l

For doing the inverse operation, python allows using the = operator on strings:

def listToStr(l):
    s = ""

    for c in l:
        s  = str(c)

    return s

CodePudding user response:

We can do something as simple as the following, which is the general case

from typing import List  # native python pkg, no need for install


def list_to_string(lst: List) -> str:
    return " ".join(lst)

def string_to_list(str_: str) -> List:
    return str_.split("")

if we want to cater to your needs that if there is an empty string, replace it with space, we shall do the following


def list_to_string(lst: List) -> str:
    ''' 
    Here we loop over the characters in a list, 
    check if character "c" is space, then append it 
    otherwise replaced with an empty string

    @param list: (List) expects a list of strings
    @returns String object of characters appended together
    '''
    return " ".join([c if c not c.isspace() else "" for c in lst])

Why am I following a one-liner approach? This is due to the fact that Pythonic approaches are better IMHO as they are more readable, compact, and neat i.e. Pythonic

Yet we can also implement the solutions using normal for loops, which is the same thing yet I prefer one-liners. And we can use string concatenation but strings are immutable objects, so every time we append to the main string we have created another string, and so on for as lengthy as the given list, which is not an optimal approach due to the increased number of variables created and memory consumption (which in your case might not be that much, but better keep an eye for that)

  • Related