【问题标题】:Split string by adresses in Python like in C (Python's String Slicing)在 Python 中按地址拆分字符串,就像在 C 中一样(Python 的字符串切片)
【发布时间】:2017-04-12 16:02:03
【问题描述】:

在 C 中,您可以通过以下方式访问字符串中您想要的位置:字符的地址:

&string[index]

例如这段代码:

#include <stdio.h>

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

将返回:

cdefgh

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

【问题讨论】:

    标签: python c python-2.7 pointers slice


    【解决方案1】:

    在 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'
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      foo = "abcdefgh"
      print foo[2:]
      

      更一般地说; foo[a:b] 表示从位置a(包括)到b(不包括)的字符。

      【讨论】:

        【解决方案3】:

        对你来说,“切片”就是答案。

        语法:s[a:b]

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

        s[a:]

        如果你想要字符串从开始到索引 b 然后使用

        s[:b+1]

        对于你的例子:

        s="abcdefgh"
        print s[2:]
        

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

        您可以从https://www.dotnetperls.com/substring-python 了解更多信息

        【讨论】:

        • 这个答案没有错,但可以改进。你能给提问者更多的信息,让他们学得更好吗?当你使用 [:] 时它叫什么?您能否将他们指向解释如何使用它的参考资料,并在您的答案中总结该参考资料?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-01
        • 2010-09-19
        • 2018-01-18
        • 2015-04-28
        • 1970-01-01
        • 2012-02-14
        相关资源
        最近更新 更多