通过Python中的地址拆分字符串,如C(Python的字符串切片)

Pie*_*pon 1 c python pointers slice python-2.7

在C中,您可以通过执行以下操作来访问包含char地址的字符串中的所需位置:

&string[index]
Run Code Online (Sandbox Code Playgroud)

例如,这段代码:

#include <stdio.h>

int main()
{
  char *foo = "abcdefgh";
  printf("%s\n", &foo[2]);
}
Run Code Online (Sandbox Code Playgroud)

将返回:

cdefgh
Run Code Online (Sandbox Code Playgroud)

有没有办法在Python中做到这一点?

Moi*_*dri 9

在Python中,它被称为字符串切片,语法是:

>>> foo = "abcdefgh"
>>> foo[2:]
'cdefgh'
Run Code Online (Sandbox Code Playgroud)

检查Python的String Document,它演示了切片功能以及python中字符串可用的其他功能.

我还建议看一下:在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'
Run Code Online (Sandbox Code Playgroud)