Pierre Capon Pierre Capon - 7 days ago 6
Python Question

split string by adresses in Python like in C

In C you can access where you want in the string with adress of the char by doing that:

&string[index]


For exmple this code :

#include <stdio.h>

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


Will return:

cdefgh


Is there a way to do that in Python ?

Answer

In Python it is known as string slicing and the syntax is:

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

Check Python's String Document which demonstrates the slicing feature along with other functions available with strings in python.

I will also suggest to take a look at: Cutting and slicing strings in Python where it is demonstrated with some very nice examples.

Here are few examples related to slicing of string:

>>> 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]   # reverse the string; my favorite ;)
'hgfedcba'
Comments