# 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.

Edited by junoh1991: ambiguity

6 Years
Discussion Span
Last Post by valorien

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.

Edited by valorien: n/a


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']
Votes + Comments
elegant solution.

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.