2013-04-23 106 views
1

我只是在學習Python和Django。Python左()相當於?

我想只得到以下字符串「關口」的終值終值始終是一個數,即COL1,COL2等

在其他語言中我能做到這一點很多方面......

left(value,3) - only leave the value after 3. 
findreplace(value, 'col', '') - fine the string col replace with blank leaving nothing but the number I need. 

所以我的問題是,Django(Python)中的我該怎麼做?(在視圖中不是模板)

又是Django嚴格嗎?我是否需要int值來使它成爲一個數字?

+3

這是稱爲「切片」,並且在Python教程中:例如:value [3:] - 將取3個字符向前...(基於0索引) – 2013-04-23 09:47:47

+0

@Jon Clements'切片'很容易,當你知道它叫什麼!那麼你能從左到右嗎? – GrantU 2013-04-23 09:50:20

+0

@ User7是的!並從右到左使用負整數:)。 – TerryA 2013-04-23 09:50:57

回答

3

您正在尋找slicing

>>> s = "Hello World!" 
>>> print s[2:] # From the second (third) letter, print the whole string 
llo World! 
>>> print s[2:5] # Print from the second (third) letter to the fifth string 
llo 
>>> print s[-2:] # Print from right to left 
d! 
>>> print s[::2] # Print every second letter 
HloWrd 

因此,對於你的例子:

>>> s = 'col555' 
>>> print s[3:] 
555 
2

如果你知道它永遠是col其次是一些數字:

>>> int('col1234'[3:]) 
1234