0

This works:

i = 1
num = '3.1.' + str(i)
if (num == '3.1.1'):
    print("correct")

And this works:

num = '3.1.1'
for content in tree.findall(".//Section/Section/Section[@SectionNumber='{}']".format(num)):
    print("correct")

But this doesn't work: (No error, just didn't print correct)

i = 1
num = '3.1.' + str(i)
for content in tree.findall(".//Section/Section/Section[@SectionNumber='{}']".format(num)):
    print("correct")

What is wrong when I combining the string? Thank you.

2
  • 1
    Are you getting an error, or is it simply failing to match? Commented May 25, 2022 at 11:58
  • @larsks No error, just didn't print "correct". Commented May 26, 2022 at 1:53

1 Answer 1

1

I can't reproduce the behavior you've described. The following Python code exercises all three examples presented in your question:

from xml.etree import ElementTree as etree

data = """
<Document>
  <Section>
      <Section>
          <Section SectionNumber="3.1.1">
              This is a test.
          </Section>
      </Section>
  </Section>
</Document>
"""


tree = etree.fromstring(data)

print("Test 1")
i = 1
num = "3.1." + str(i)
if num == "3.1.1":
    print("correct")
print()

print("Test 2")
num = "3.1.1"
for content in tree.findall(
    ".//Section/Section/Section[@SectionNumber='{}']".format(num)
):
    print("correct")
print()

print("Test 3")
i = 1
num = "3.1." + str(i)
for content in tree.findall(
    ".//Section/Section/Section[@SectionNumber='{}']".format(num)
):
    print("correct")
print()

Running the above code produces:

Test 1
correct

Test 2
correct

Test 3
correct

If you run this code and get different results, or if you can update your question to include a complete, runnable example that produces the behavior you've described, I would be happy to take a closer look.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.