Slicing a string in Python

Question:

When we need to slice a string at a particular location, we need to know the index from where we want to.

For example, in the string:

>>> s = 'Your ID number is: 41233'

I want to slice the string starting from : and get the number.

Sure I can count at what index : is and then slice, but is that really a good approach?

Of course I can do a s.index(':'). But that would be an extra step, so I came up with something like:

>>> print s[(s.index(':')+2):]
41233

But somehow I don’t like the looks of it.

So my question is, given a long string which you want to slice, how do you find the index from where to begin the slicing in the easiest and most readable way? If there is a trick to do it orally, I would love to know that.

Asked By: user225312

||

Answers:

Perhaps you could use split():

>>> s = 'Your ID number is: 41233'
>>> print s.split(":")[1].strip()
41233
Answered By: Greg Hewgill

Another approach is 'Your ID number is: 41233'.split(':')[1].strip().

Answered By: khachik
text, sep, number = 'Your ID number is: 41233'.partition(':')
print number

works too. But it won’t fail if the separator is not in the string.

That unpacking works for split too:

text, number = 'Your ID number is: 41233'.split(':',1)
Answered By: Jochen Ritzel

So my question is, given a long string which you want to slice, how do you find the index from where to begin the slicing in the easiest and most readable way?

When “where to begin the slicing” is a specific symbol, you don’t; instead you just as Python to split the string up with that symbol as a delimiter, or partition it into the bits before/within/after the symbol, as in the other answers. (split can split the string into several pieces if several delimiters are found; partition will always give three pieces even if the symbol is not there at all.)

If there is a trick to do it orally, I would love to know that.

I really don’t think you mean “orally“. 🙂

Answered By: Karl Knechtel

I wouldn’t use slicing at all unless there’s some other compelling reason you want to do so. Instead, this sounds like a perfect job for re the regular expression module in the standard library. Here’s an example of using it to solve your problem:

import re
compile_obj = re.compile(r'Your ID number is:s(?P<ID>d+)')

s = 'Your ID number is: 41233'
match_obj = compile_obj.search(s)
if match_obj:
    print match_obj.group('ID')
# 41233
Answered By: martineau

Recently came across partition

string = "Your ID number is: 41233"

string = string.partition(':')

print string[2]
Answered By: Mike Anson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.