Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (240 points)
Hi all, is there a way in which I can substring a particular string in Python? I want to get the new string from say the 2nd character to EOL. How can I do this?

All help appreciated!

2 Answers

0 votes
by (300 points)

Hey. It can be done in a simple way. Please check the code below to do the same.

Code:

>>> x = "Hello World!"

>>> x[2:]

'llo World!'

>>> x[:2]

'He'

>>> x[:-2]

'Hello Worl'

>>> x[-2:]

'd!'

>>> x[2:-2]

'llo Worl'

 

This is called slicing officially. Widely used concept and pretty useful too! Hope this helps!

0 votes
by (106k points)
edited by

Normally we use the slice method to getting a substring from a string in Python

But like PHP and Perl, Python also has a function which is Substr() it works as follows:-

s = Substr(s, beginning, LENGTH)

If you are familiar with Python then you must know that it expects beginning and one after END. 

So the correct replacement for Substr(s, beginning, LENGTH) is

s = s[ beginning : beginning + LENGTH]

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+2 votes
3 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...