Home » Python » python – How can I replace a nested list of phrases with dashes?-Exceptionshub

python – How can I replace a nested list of phrases with dashes?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

If I have

LIST=[['SPORTS','NEW YORK JETS']]

and I want to replace the second element of my sublist (NEW YORK JETS) to ___ ____ ____, how can I do that?

So far, I have:

hide = ""
for l in LIST:
 if l[1] != " ":
  hide = hide + "_"
else:
  hide = hide + " "
print(hide)

This doesn’t give me the desired output. I’d appreciate any suggestions.

Thank You!

How to&Answers:

You have to loop over the characters in the string in a nested loop, and replace the non-space characters with _.

result = []
for word1, word2 in LIST:
    hide = ""
    for c in word2:
        if c == " ":
            hide += " "
        else:
            hide += "_"
    result.append([word1, hide])

Answer:

try with this

LIST=[['SPORTS','NEW YORK JETS']]
hide = []
for l in LIST:
 sub = []
 for sub_l in l : 
   s = ""
   for c in sub_l : 
     if c != " " :
      s += "_"
     else :
      s += " "
   sub.append(s)
hide.append(sub)

print(hide)

Answer:

You can use built-in function enumerate and filter list elements based on index:

lizt = [
    ['sports', 'new york jets', 'even more values if you want'],
    ['sports2', 'new york jets2', 'even more values if you want2'],
    # ...
]

hide_list = []
for nested_list in lizt:
    hide_nested_list = []
    for index, value in enumerate(nested_list):
        if index == 1:
            hide_nested_list.append('___ ____ ____')
        else:
            hide_nested_list.append(value)
    hide_list.append(hide_nested_list)

print(hide_list)

It is way shorter with list comprehensions:

lizt = [
    ['sports', 'new york jets', 'even more values if you want'],
    ['sports2', 'new york jets2', 'even more values if you want2'],
    # ...
]

hide_list = [
    [v for i, v in enumerate(l) if i != 1 else '___ ____ ____'] for l in lizt
]

print(hide_list)

Answer:

You can build a new list using list comprehension and calculating the length of each word replacing them with _ like this:

values = [['SPORTS','NEW YORK JETS'], ['SPORTS2','NEW YORK JETS2']]
hidden = [
    [ 
        v[0], 
        ' '.join('_'*len(word) for word in  v[1].split())
    ] for v in values
]

print(hidden)

>>> [['SPORTS', '___ ____ ____'], ['SPORTS2', '___ ____ _____']]