Pierre Capon Pierre Capon - 1 year ago 65
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:


For exmple this code :

#include <stdio.h>

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

Will return:


Is there a way to do that in Python ?

Answer Source

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

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

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
>>> foo[:3]     # from start to 3rd index (excluding 3rd index)
>>> foo[2:4]    # start from 2nd index till 4th index (excluding 4th index)
>>> foo[2:-1]   # start for 2nd index excluding last index
>>> foo[-3:-1]  # from 3rd last index to last index ( excluding last index)
>>> foo[::-1]   # reverse the string; my favorite ;)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download