1

I have a str in python like below. I want extract a substring from it.

table='abc_test_01'

number=table.split("_")[1]

I am getting test as a result.

What I want is everything after the first _.

The result I want is test_01 how can I achieve that.

2
  • 2
    table.partition("_")[2] Commented May 8, 2017 at 18:41
  • Or: table.split('_', 1)[1] Commented May 8, 2017 at 18:57

5 Answers 5

1

Here is the code as already given by many of them

table='abc_test_01'
number=table.split("_",1)[1]

But the above one may fail in situations when the occurrence is not in the string, then you'll get IndexError: list index out of range

For eg.

table='abctest01'
number=table.split("_",1)[1]

The above one will raise IndexError, as the occurrence is not in the string

So the more accurate code for handling this is

table.split("_",1)[-1]

Therefore -1 will not get any harm because the number of occurrences is already set to one.

Hope it helps :)

Sign up to request clarification or add additional context in comments.

Comments

1

To get the substring (all characters after the first occurrence of underscore):

number = table[table.index('_')+1:]
# Output: test_01

Comments

1

You could do it like:

import re
string = "abc_test_01"

rx = re.compile(r'[^_]*_(.+)')
match = rx.match(string).group(1)
print(match)

Or with normal string functions:

string = "abc_test_01"

match = '_'.join(string.split('_')[1:])
print(match)

Comments

1

Nobody mentions that the split() function can have an maxsplit argument:

str.split(sep=None, maxsplit=-1)

return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

So the solution is only:

table.split('_', 1)[1]

Comments

1

You can try this:

Edit: Thanks to @valtah's comment:

table = 'abc_test_01'
#final = "_".join(table.split("_")[1:])
final = table.split("_", 1)[1]
print final 

Output:

'test_01'

Also the answer of @valtah in the comment is correct:

final = table.partition("_")[2]
print final 

Will output the same result

2 Comments

"_".join(table.split("_")[1:]) makes so many unnecessary operations: splitting, slicing, joining, when all you need is to set maxsplit to 1. So table.split("_", 1)[1] also works.
Great answer again! i didn't know that i can do this with str.split(). I'll edit my answer. Thanks for your comment.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.