代码之家  ›  专栏  ›  技术社区  ›  Leon Gaban

如何在Python中将简单字符串转换为int(金字塔)

  •  1
  • Leon Gaban  · 技术社区  · 12 年前

    尝试在Python中将好友id“5”转换为数字

    当我试图将此字符串转换为数字时,我收到一个错误:

    [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"'
    

    蟒蛇

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

    我找到了上面尝试的代码 here here 。两者都不起作用,都会导致上述错误。

    你知道我做错了什么吗?我不想仅仅为了转换这个而创建一个新的def,难道没有办法用几个字符来实现吗?

    2 回复  |  直到 12 年前
        1
  •  3
  •   alecxe    12 年前

    "5" 在双引号中, strip 他们:

    int(friend.strip('"'))
    

    演示:

    >>> 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
    
        2
  •  2
  •   locoyou    12 年前

    因为你的绳子 "5" 而不是 5 ,注意双引号。