You are trying to get what's after ID=
?
I'm not sure about performance (you'll have to benchmark on your own data) but I would do this:
def get_id(string):
try:
id = str.split('ID=')[1].strip()
return id
except IndexError:
return None
string = "0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\n"
id = get_id(string)
This only works if there are 0 or 1 ID=
parts. If there are 2 or more only the first one gets returned.
Edit:
This is how I would do benchmarks (I might be wrong, I don't have much experience in this):
>>> #string with escaped '\n' at the end:
>>> string = '0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\\n'
>>> #original regex + getting the match object:
>>> timeit.timeit(stmt="re.search(r'.*ID=(\d+)', '{}').group(1)".format(string), setup="import re")
3.4012476679999963
>>> #original regex only:
>>> timeit.timeit(stmt="re.search(r'.*ID=(\d+)', '{}')".format(string), setup="import re")
2.560870873996464
>>> #alternative regex + match object (had to use c-style string formatting):
>>> timeit.timeit(stmt="re.search(r'ID=(\d{15})', '%s').group(1)" % string, setup="import re")
3.0494329900029697
>>> #alternative regex only:
>>> timeit.timeit(stmt="re.search(r'ID=(\d{15})', '%s')" % string, setup="import re")
2.2219171980032115
>>> #str.split:
>>> timeit.timeit(stmt="'{}'.split('ID=')[1].strip()".format(string))
1.127366863998759
I think these are the benchmarks for the relevant parts. This is on a CoreDuo MacBook Pro and your results may vary. It's been my experience that using methods from the standard library usually yields the best results.
On the other hand, this is important only if you have a ton of data to process. Otherwise a more flexible but "slower" way of doing things might be better.
print
will be more expensive then anything else and relative to that no other change will really matter. \$\endgroup\$self
andreturn
ing the answer. If you want help you need to show your actual code! As it stands this is totally useless. \$\endgroup\$