Python: Add Same Prefix to All Elements in List
Asked Answered
R

3

5

Let's say I have the following Python List:

['7831-0', nan, '3165-0', '7831-0', '7831-1'] 

I want to add the same prefix ('ADD_' to each element in the above list. I also want to remove the nan from my list. My desired output list is as follows:

list = ['ADD_7831-0', 'ADD_3165-0', 'ADD_7831-0', 'ADD_7831-1']

I tried the following code:

prefix_ADD = 'ADD_'

new_list = [prefix_ADD + x for x in list]

But I get the following error:

TypeError: must be str, not float
Revolt answered 24/4, 2019 at 22:49 Comment(1)
@Pine-Nuts[0] - interested in pandas?Spatterdash
C
7

[prefix_ADD + x for x in list if not str(x) == "nan"]

Is one way you could filter out nan

Carpogonium answered 24/4, 2019 at 22:52 Comment(0)
M
3
your_list = ['7831-0', float('nan'), '3165-0', '7831-0', '7831-1']
print(your_list)  # ['7831-0', nan, '3165-0', '7831-0', '7831-1']
prefix_ADD = 'ADD_'
new_list = [prefix_ADD + x for x in your_list if isinstance(x, str)]
print(new_list)  # ['ADD_7831-0', 'ADD_3165-0', 'ADD_7831-0', 'ADD_7831-1']
Meath answered 24/4, 2019 at 22:51 Comment(0)
H
1

Maybe a less elegant solution but how about this:

new_list=[]
old_list = ['7831-0', nan, '3165-0', '7831-0', '7831-1']

prefix_ADD = 'ADD_'

for x in old_list:
    if x != nan:
        new_list.append(prefix_ADD + x)

print(new_list)
# ['ADD_7831-0', 'ADD_3165-0', 'ADD_7831-0', 'ADD_7831-1']
Hofstetter answered 24/4, 2019 at 23:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.