2014-03-27 37 views
1

尝试转换朋友ID =“5”成数在Python如何简单的字符串转换成int类型的Python(金字塔)

当我尝试这个字符串转换为数字我得到一个错误:

[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,是不是有办法用几个字符来做到这一点?

回答

3

"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 
+1

做'friend.strip()'会让你陷入困境。确保你意识到友谊的界限。 –

+0

或使用'int(eval(s))'。但也可能很危险。如果你有混合str/int,int(eval(str(s)))'。 – fredtantini

+0

谢谢!我来自JavaScript,“”意思是一个字符串,在Python中仍然很新颖:) –

2

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