【问题标题】:How to convert simple string into an int in Python (pyramid)如何在 Python(金字塔)中将简单字符串转换为 int
【发布时间】:2014-03-27 15:39:08
【问题描述】:

尝试在 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"'

Python

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

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

你知道我做错了什么吗?我不想创建一个新的 def 只是为了转换它,有没有办法用几个字符来做到这一点?

【问题讨论】:

    标签: python string integer pyramid


    【解决方案1】:

    "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
    

    【讨论】:

    • 执行friend.strip() 可能会给您带来麻烦。确保您了解友谊的界限。
    • 或使用int(eval(s))。但也可能很危险。如果你混合了 str/int,int(eval(str(s))).
    • 谢谢!我来自 javascript 和 "" 意思是一个字符串,在 Python 中仍然很新:)
    • ""'' 在 Python 中也表示字符串,但就像在 JavaScript 中一样,如果你将它们嵌套在 '""'"''" 中,你会得到一个带有引号的字符串。无论哪种语言,'"5"' != "5"
    【解决方案2】:

    这是因为您的字符串是"5" 而不是5,请注意双引号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-17
      • 2011-04-28
      • 2013-09-16
      • 2011-04-26
      • 1970-01-01
      • 2014-12-22
      • 2011-02-04
      相关资源
      最近更新 更多