# I wanted to change the question.

I have a list something like this:

For this list, if the element in the list starts with N, i want '+' to be inserted before the integer. If the element in the list starts with S, I want '-' to be inserted before the integer.

For example, I want the above list to look like this:

I can't use any module. Can anyone help me with this one?

# made some correction.

That is not list of elements any type I know.

Here's my quick and dirty solution:

list1= ['NNW 30', 'SE 15', 'SSW 60', 'NNE 70', 'N 10']

for index, item in enumerate(list1):
    if item.startswith('N'):
        list1[index] = "+" + item[-2:]
    elif item.startswith('S'):
        list1[index] = "-" + item[-2:]


Notice the use of startswith(), and the negative used to slice the letters in each list item. This will not work if the number has more or less than 2 digits, but it can easily be changed to treat that as well - use that as an exercise.

It might be safer to extract the numeric value ...

list1= ['NNW 30', 'SE 15', 'SSW 60', 'NNE 70', 'N 10']

list2 = []
for item in list1:
    s = ""
    for c in item:
        # extract numeric value
        if c in '1234567890.-':
            s += c
    if item[0] == 'N':
        s = '+' + s
    if item[0] == 'S':
        s = '-' + s

print(list2)  # ['+30', '-15', '-60', '+70', '+10']
commented: elegant solution. +1

Excellent solution Vegaseat, definitely better than mine.
"c in '123...'" is very useful. Thanks for sharing.

Ok, if we are going to give (again) ready answer:

>>> values = [('+' if item.startswith('N') else ('-' if item.startswith('S') else '')) + item.rsplit(' ', 1)[-1] for item in list1]
>>> values
['+30', '-15', '-60', '+70', '+10']

Great answer Tony, though I'll need some time to fully comprehend it ;-).

What would you recommend when faced with such questions? I'm still learning the ropes here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.