Home > Net >  How to create whitespace between certain list elements?
How to create whitespace between certain list elements?

Time:07-07

I found a post asking about how to create whitespace in all list elements (Adding spaces to items in list (Python)), but I haven't found any posts asking about how to create whitespace in only specific elements of a list.

I'm wondering how to create a space between certain element characters in a list.

If I have a list like this:

lst = ['a', 'bb', 'c', 'bb']

How can I make a new list with a space between all 'bb' occurrences in a list to look like this?:

lst_new = ['a', 'b b', 'c', 'b b']

I've tried using .replace('bb', 'b" "b'), but I get 'b' and 'b' as separate list elements. Is there a specific notation for "whitespace" in Python? Or is there another way to approach this?

CodePudding user response:

lst = ['a', 'bb', 'c', 'dd']

lst_new = []

for elem in lst:
    if len(elem) > 1:
        lst_new.append(' '.join(list(elem)))
    else:
        lst_new.append(elem)
    
print(lst_new)

Here's a very simple and easy to understand way to do it. The main idea is to check if the length of the elem is greater than 1, then use list to "split" the string. You can then join the string with a whitespace by using join.

  • Related