gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:10 25 4
gpt4 key购买 nike

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

&string[index]

例如这段代码:

#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 中 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'

关于python - 在 Python 中按地址拆分字符串,就像在 C 中一样(Python 的字符串切片),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40852650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com