2016-11-28 68 views

回答

9

在Python它被稱爲串切片和語法是:

>>> foo = "abcdefgh" 
>>> foo[2:] 
'cdefgh' 

檢查Python's String Document這表明與可用在Python等功能沿切片功能。

我也會建議看看:Cutting and slicing strings in Python這裏有一些很好的例子。

下面是相關的字符串的切片幾個例子:

>>> foo[2:]  # start from 2nd index till end 
'cdefgh' 
>>> foo[:3]  # from start to 3rd index (excluding 3rd index) 
'abc' 
>>> foo[2:4] # start from 2nd index till 4th index (excluding 4th index) 
'cd' 
>>> foo[2:-1] # start for 2nd index excluding last index 
'cdefg' 
>>> foo[-3:-1] # from 3rd last index to last index (excluding last index) 
'fg' 
>>> foo[1:6:2] # from 1st to 6th index (excluding 6th index) with jump/step of "2" 
'bdf' 
>>> foo[::-1] # reverse the string; my favorite ;) 
'hgfedcba' 
2

這是你如何做到這一點:

foo = "abcdefgh" 
print foo[2:] 

更普遍; foo[a:b]表示從位置a(包括)到b(不包括)的字符。

1

對於你的問題「切片」就是答案。

語法:s[a:b]

如果你想串從指數至年底開始,然後使用

s[a:]

,如果你想這會給你從索引的字符串B-1 字符串從開始到索引b再使用

s[:b+1]

併爲您的示例:

s="abcdefgh" 
print s[2:] 

將打印cdefgh,因此是回答你的問題。

你可以從https://www.dotnetperls.com/substring-python

+0

這個答案閱讀更多關於它是沒有錯的,但它可以改善。你能否提供更多的信息,讓他們學得更好?當你使用[:]時叫什麼?你能否給他們提供一個解釋如何使用它的參考,並在你的答案中總結這個參考? –

+0

提高答案的質量。謝謝。 –