Yigit Pektasoglu
Yigit Pektasoglu

Reputation: 13

Adding a symbol to list elements

I'm trying to build a lists and I have list forms like :

numbers=['1','2','3']

I want to transform into :

numbers=['-1-','-2-','-3-']

I may need to change it later to

numbers=['-1-','(2)','-3-']

and I will choose which is gonna be . Is there any method or function to do that? . Sry for my english thanks in advice

Upvotes: 1

Views: 1762

Answers (2)

CoderMuffin
CoderMuffin

Reputation: 608

Try using this, it's a bit different to the last but ultimately the same:

def formatList(listIn,selections):
    l=[]
    for i in range(len(listIn)):
        if not i in selections:
            l.append('-'+str(listIn[i])+'-')
        else:
            l.append('('+str(listIn[i])+')')
    return l

where selections as an input would be something like [2,'''other selections'''] (if you don't know, '''This is a comment in python (so is this #blahblah but it has to be on the same line)''')

Upvotes: 0

Felix
Felix

Reputation: 1905

The first case is solved by this list comprehension

l = [f'-{n}-' for n in numbers]

The second one by this for loop, which resembles the previous list comprehension

l = []
for i, n in enumerate(numbers):
    if i % 2 == 0:
        l.append(f'-{n}-')
    else:
        l.append(f'({n})')

Alternatively you can write the for loop as a list comprehension as well

[f'-{n}' if i % 2 == 0  else f'-({n})-' for i, n in enumerate(numbers)]

Upvotes: 2

Related Questions