2014-03-27 18 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,注意雙引號。