在C語言中,你可以通過這樣做,與焦炭的ADRESS訪問您要在字符串中分割字符串在Python中不會忽略像C(Python的字符串的切片)
&string[index]
對於exmple這段代碼:
#include <stdio.h>
int main()
{
char *foo = "abcdefgh";
printf("%s\n", &foo[2]);
}
返回結果:
cdefgh
有沒有辦法做到這一點在Python?
在C語言中,你可以通過這樣做,與焦炭的ADRESS訪問您要在字符串中分割字符串在Python中不會忽略像C(Python的字符串的切片)
&string[index]
對於exmple這段代碼:
#include <stdio.h>
int main()
{
char *foo = "abcdefgh";
printf("%s\n", &foo[2]);
}
返回結果:
cdefgh
有沒有辦法做到這一點在Python?
在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'
這是你如何做到這一點:
foo = "abcdefgh"
print foo[2:]
更普遍; foo[a:b]
表示從位置a
(包括)到b
(不包括)的字符。
對於你的問題「切片」就是答案。
語法:s[a:b]
如果你想串從指數至年底開始,然後使用
s[a:]
,如果你想這會給你從索引的字符串B-1 字符串從開始到索引b再使用
s[:b+1]
併爲您的示例:
s="abcdefgh"
print s[2:]
將打印cdefgh
,因此是回答你的問題。
這個答案閱讀更多關於它是沒有錯的,但它可以改善。你能否提供更多的信息,讓他們學得更好?當你使用[:]時叫什麼?你能否給他們提供一個解釋如何使用它的參考,並在你的答案中總結這個參考? –
提高答案的質量。謝謝。 –