Python comparing strings, problem with endlines

Hi guys I have two different strings. One of these stings is a description and the other one is a template.

I want to check if the template is inclued in the description.

The Problem is that I cant just do

if template in description:
   print("template is included")
   return True
else: raise Exception("exception test23")

Answer

To convert your whole template into a regular expression, you will need to escape it using re.escape. Within that expression, you will want some parts to be treated as wildcards so that content may vary in the document (i.e. “X” between brackets). You can alter the escaped pattern to replace placeholders with expressions that will account for the variations:

Between your template and the actual content, there is also a few spaces on empty lines that create an invisible difference. This may just be a copy/paste issue but in case it is a legitimate difference, I made an additional alteration to the template pattern to ignore extra spaces at the beginning of each line.

import re
pattern = template.replace("[ ]","[CHECK]") # allow variable content between []
pattern = re.escape(pattern).replace("CHECK",r".+") # CHECK-->regular exp.
pattern = pattern.replace("n","n *") # for extra spaces at begining of lines

if re.search(pattern,document):
    print("contains template")
else:
    print("does not contain template")

output:

template="""<details>

<summary> <b>Technical Template</b>
</summary>

- [ ] Formal

##### Formal
- Is the document template used properly and consistently?
- Has the generated pdf file been checked?

##### Content
- Is the user documentation clear, correct and complete?

</details>"""

document = """| costumer-check  |/ | 
 | --- | --- | 

<details>

<summary> <b> Completeness</b>
</summary>

- [x] Formal

</details>


<details>

<summary> <b>Technical Template</b>
</summary>

- [x] Formal
- [x] Content

##### Formal
- Is the document template used properly and consistently?
- Has the generated pdf file been checked?
 
</details>"""

# this prints: contains template

Leave a Reply

Your email address will not be published. Required fields are marked *