简体   繁体   中英

Compare each bit of a string in Python

I have a SQL query which needs to be converted into Python. I'm stucked in working on one condition.

if id != '[0-9]{4}[a-z]{2}0[0-9]{1}' 

(Explanation [First 4 numbers] + [2 alphabet] + [0] + [0-9] + [1]) print(id)

How can I check this condition in Python?

You can use re module to do that:

import re

if not re.match(r'[0-9]{4}[a-z]{2}0[0-9]{1}', id):
    # do something

Edit:

'r' here is not required but it's recommended. it means raw string (nothing in the string should be escaped), take a look at the following example:

>>> print('test\n')
test

>>> print(r'test\n')
test\n

For more details, please take a look at re documentation.

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