issue with regular expressions

Matt Wheeler m at funkyhat.org
Tue Oct 22 05:29:27 EDT 2019


On 2019年10月22日, 09:44 joseph pareti, <joepareti54 at gmail.com> wrote:
> the following code ends in an exception:
>> import re
> pattern = 'Sottoscrizione unica soluzione'
> mylines = [] # Declare an empty list.

with open ('tmp.txt', 'rt') as myfile: # Open tmp.txt for reading text.
> for myline in myfile: # For each line in the file,
> mylines.append(myline.rstrip('\n')) # strip newline and add to
> list.
> for element in mylines: # For each element in the list,
> # print(element)
> match = re.search(pattern, element)
> s = match.start()
> e = match.end()
> print(element[s:e])
>>>> F:\October20-2019-RECOVERY\Unicredit_recovery\tmp_re_search>c:\Users\joepareti\Miniconda3\pkgs\python-3.7.1-h8c8aaf0_6\python.exe
> search_0.py
> Traceback (most recent call last):
> File "search_0.py", line 10, in <module>
> s = match.start()
> AttributeError: 'NoneType' object has no attribute 'start'
>> any help? Thanks
>
Check over the docs for re.match again, you'll see it returns either a
Match object (which is always truthy), or None.
So a simple solution is to wrap your attempts to use the Match object in
```
if match:
 ...
```
>


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /