-2

I want to test if a string has a negative leading character, and then delete that character if True.

I've tried:

value_a = "-50.1342"
temp_a = value_a.split(".") #needed for other purposes
if temp_a[0].startswith('-'):
  del temp_a[0]

print temp_a

The result is an empty []. What could be the reason...?

Yafim Simanovsky
  • 531
  • 7
  • 26

4 Answers4

2

You have a list containing 1 element, the string "-50".

What you want to do is mutate that string, like this:

temp_a[0] = temp_a[0].replace("-", '')

Rafael Barros
  • 2,738
  • 1
  • 21
  • 28
1

The output is zero because when you do del temp_a[0] You are not deleting the negative you are deleting the -50. So once you print it It makes it zero. This is shown in the repl.it - https://repl.it/@RithvikKasarla/VapidExternalRuntimes

To make it delete the negative try something like this.

value_a = "-50.1342"
temp_a = value_a.split(".") #needed for other purposes
if temp_a[0].startswith('-'):
  temp_a[0] = str(int(temp_a[0])*-1)
print temp_a

Doing this makes the output ["50","1342"]

RithvikK
  • 111
  • 13
1

From your description, it sounds like this might be what you want.

value_a = "-50.1342"
temp_a = value_a.split(".") #needed for other purposes

if temp_a[0][0] == '-':
    temp_a[0] = temp_a[0][1:]

print temp_a

This gives me

['50', '1342']
0

Try this:

value_a = "-50.1342"
value_a=value_a.replace("-",'')

Which will remove it given that value_a is a number.

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44