13

Lets Say we have Zaptoit:685158:[email protected]

How do you split so it only be left 685158:[email protected]

0

7 Answers 7

13
>>> s = 'Zaptoit:685158:[email protected]'
>>> s.split( ':', 1 )[1]
'685158:[email protected]'
Sign up to request clarification or add additional context in comments.

1 Comment

Note that it's not really good practice to use the variable name "str" since str() is a builtin.
5

Another solution:

s = 'Zaptoit:685158:[email protected]'
s.split(':', 1)[1]

Comments

5

Another method, without using split:

s = 'Zaptoit:685158:[email protected]'
s[s.find(':')+1:]

Ex:

>>> s = 'Zaptoit:685158:[email protected]'
>>> s[s.find(':')+1:]
'685158:[email protected]'

Comments

3

As of Python 2.5 there is an even more direct solution. It degrades nicely if the separator is not found:

>>> s = 'Zaptoit:685158:[email protected]'
>>> s.partition(':')
('Zaptoit', ':', '685158:[email protected]')

>>> s.partition(':')[2]
'685158:[email protected]'

>>> s.partition(';')
('Zaptoit:685158:[email protected]', '', '')

1 Comment

This is exactly what I was looking for. I knew about split(), but hadn't run across partition() before. Thanks!
1

Following splits the string, ignores first element and rejoins the rest:

":".join(x.split(":")[1:])

Output:

'685158:[email protected]'

Comments

0
s = re.sub('^.*?:', '', s)

7 Comments

@PEZ: better being stopping the match on the first ':' instead of the last one
@orip: I think you are mistaken -- the question mark makes it a non-greedy match that will stop at the first colon, as intended
Yeah, I think Nick means something else.
It doesn't matter in this case, but in general, if you have choice between a negated character class and a reluctant quantifier (eg, '.*?'), the char class tends to be faster, less memory-intensive, and most importantly, more predictable.
Sorry, forgot to compile the regexes outside the for loop. When doing this, the negated character class version takes 34% less time. I also tried to compile the code with cython, statically declaring the int:s and double:s (which should reduce overhead). Then time is reduced by 40%, so the negated character class clearly is faster.
|
0

Use the method str.split() with the value of maxsplit argument as 1.

mailID = 'Zaptoit:685158:[email protected]' 
mailID.split(':', 1)[1]

Hope it helped.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.