Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a substring of a string in Python?

Is there a way to substring a string in Python, to get a new string from the third character to the end of the string?

Maybe like myString[2:end]?

If leaving the second part means 'till the end', and if you leave the first part, does it start from the start?

like image 958
Joan Venge Avatar asked Mar 19 '09 17:03

Joan Venge


People also ask

How do you extract a substring from a string in python?

In python, extracting substring form string can be done using findall method in regular expression ( re ) module.

How do you find a specific substring in a string?

To locate a substring in a string, use the indexOf() method. Let's say the following is our string. String str = "testdemo"; Find a substring 'demo' in a string and get the index.

How do you slice part of a string in python?

Slicing Strings You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.


2 Answers

>>> x = "Hello World!" >>> x[2:] 'llo World!' >>> x[:2] 'He' >>> x[:-2] 'Hello Worl' >>> x[-2:] 'd!' >>> x[2:-2] 'llo Worl' 

Python calls this concept "slicing" and it works on more than just strings. Take a look here for a comprehensive introduction.

like image 169
Paolo Bergantino Avatar answered Sep 27 '22 23:09

Paolo Bergantino


Just for completeness as nobody else has mentioned it. The third parameter to an array slice is a step. So reversing a string is as simple as:

some_string[::-1] 

Or selecting alternate characters would be:

"H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World" 

The ability to step forwards and backwards through the string maintains consistency with being able to array slice from the start or end.

like image 31
Endophage Avatar answered Sep 28 '22 00:09

Endophage