Message359160
This was discussed recently on the Python-ideas mailing list.
https://mail.python.org/archives/list/python-ideas@python.org/thread/M2OZCN5C26YUJJ4EXLIIXHQBGF6IM5GW/#H3GURL35C7AZ3ZBK6CQZGGCISUZ42WDV
I agree with Raymond that this is an education problem. There are occurrences of `findall(...)[0]` in real code, but most of this code has not very high quality. In all cases re.search() can be used. In some cases the code can be rewritten in much more efficient way, using a single regular expression, for example:
- if re.search('^(\w+) (\w+)$', parcel.owner):
- last, first = re.findall( '(\w+) (\w+)',parcel.owner )[0]
- elif re.search('^(\w+) (\w+) (\w+)$', parcel.owner):
- last, first, middle = re.findall( '(\w+) (\w+) (\w+)',parcel.owner )[0]
- elif re.search('^(\w+) (\w+) & (\w+)$', parcel.owner):
- last, first = re.findall( '(\w+) (\w+)',parcel.owner )[0]
- elif re.search('^(\w+) (\w+) (\w+) &: (\w+)$', parcel.owner):
- last, first, middle = re.findall( '(\w+) (\w+) (\w+)',parcel.owner )[0]
- elif re.search('^(\w+) (\w+) & (\w+) (\w+)$', parcel.owner):
- last, first = re.findall( '(\w+) (\w+)',parcel.owner )[0]
- elif re.search('^(\w+) (\w+) (\w+) &: (\w+) (\w+)$', parcel.owner):
- last, first, middle = re.findall( '(\w+) (\w+) (\w+)',parcel.owner )[0]
- elif re.search('^(\w+) (\w+) & (\w+) (\w+) (\w+)$', parcel.owner):
- last, first = re.findall( '(\w+) (\w+)',parcel.owner )[0]
- elif re.search('^(\w+) (\w+) (\w+) &: (\w+) (\w+) (\w+)$', parcel.owner):
- last, first, middle = re.findall( '(\w+) (\w+) (\w+)', parcel.owner )[0]
+ m = re.fullmatch('(\w+) (\w+)(?: (\w+))?(?: &(?: \w+){1,3})?', parcel.owner)
+ if m:
+ last, first, middle = m.groups()
But even using `findall(...)[0]` is not always so bad, because in many cases findall() returns a list containing a single string.
Adding re.findfirst() will not automatically fix all existing code which uses `findall(...)[0]`. This is an education problem, you need to teach people to use the more appropriate function, and if you can teach about re.findfirst(), why can't you teach about re.search()? |
|
Date |
User |
Action |
Args |
2020-01-01 14:47:08 | serhiy.storchaka | set | recipients:
+ serhiy.storchaka, rhettinger, ezio.melotti, mrabarnett, apalala |
2020-01-01 14:47:08 | serhiy.storchaka | set | messageid: <1577890028.4.0.327811696598.issue39165@roundup.psfhosted.org> |
2020-01-01 14:47:08 | serhiy.storchaka | link | issue39165 messages |
2020-01-01 14:47:08 | serhiy.storchaka | create | |
|