简体   繁体   中英

How to get sub string from a string in python using split or regex

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.

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)

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

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

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

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]

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM