按 Python 中的地址拆分字符串,就像在 C 中一样(Python 的字符串切片)

Split string by adresses in Python like in C (Python's String Slicing)

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

&string[index]

例如这段代码:

#include <stdio.h>

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

会 return:

cdefgh

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

您可以这样做:

foo = "abcdefgh"
print foo[2:]

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

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

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

检查 Python's String Document,它演示了切片功能以及 python 中 strings 提供的其他功能。

我还建议看一下: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'

你的问题"slicing"就是答案。

语法:s[a:b]

这会给你一个从索引a到b-1的字符串 如果您希望字符串从索引开始直到结束,请使用

s[a:]

如果你想要从开始到索引 b 的字符串,那么使用

s[:b+1]

以你的例子为例:

s="abcdefgh"
print s[2:]

将打印 cdefgh,因此是您问题的答案。

您可以从 https://www.dotnetperls.com/substring-python

阅读更多相关信息