Frage

Trying to convert friend id "5" into a number in Python

When I try to convert this string into a number I get an error:

[Applications/MAMP/htdocs/WhoAt/env/www/www/views/contacts/contacts.py line:63]
un_friend()
     ->contact = int(friend)

ValueError: invalid literal for int() with base 10: '"5"'

Python

## friend is "5" str
friend = self.request.body
## Tried:
contact = int(friend)
## and just:
int(friend)

I found the code I tried above here and here. Neither work and both cause the error above.

Do you see what I'm doing wrong? I don't want to have to create a new def just to convert this, isn't there a way to do this with a few characters?

War es hilfreich?

Lösung

"5" is in double quotes, strip them:

int(friend.strip('"'))

Demo:

>>> s = '"5"'
>>> int(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '"5"'
>>> int(s.strip('"'))
5

Andere Tipps

It is because your string is "5" instead of 5, notice the double quote.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top