1

I have some trouble with my code. In "line1 and line2" before the text in file have some spaces, how i can ignore them?

Ex.:

<server xmlns="urn:jboss:domain:1.2">
         </handlers>
        </root-logger>
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:naming:1.1">
    <bindings>

And these spaces interfere with code to find line1 and line2.

Below is my code

with open("xxx", "r+") as f:
a = [x.rstrip() for x in f]
index = 1
line1 = '<subsystem xmlns="urn:jboss:domain:naming:1.1">'
line2 = "<bindings>"
for item in a:
    if item.startswith(line1 and line2):
        a.insert(index, '<simple name="java:global/nbs/app/portal/config/routes"\n\tvalue="C:\\nbs\\app\\portal\\routes.properties"/>')
        break
    index += 1
f.seek(0)
for line in a:
    f.write(line + "\n")
  • Possible duplicate of [How do I remove leading whitespace in Python?](https://stackoverflow.com/questions/959215/how-do-i-remove-leading-whitespace-in-python) – Van Peer Oct 24 '17 at 04:52
  • Possible duplicate of [Trimming a string in Python](https://stackoverflow.com/questions/761804/trimming-a-string-in-python) – jwpfox Nov 18 '17 at 02:36

2 Answers2

1

The lstrip() method will remove leading whitespaces, newline and tab characters on a string beginning:

>>> '     hello world!'.lstrip()
'hello world!

Reference: How do I remove leading whitespace in Python?

kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
  • No, i need ignore spaces not in my script, i need ignore spaces in file. When i delete spaces, the script is working fine, but if i don't delete them, the script does not find these lines. – Anuar Mukatov Oct 24 '17 at 05:30
0

Change this

a = [x.rstrip() for x in f]

into this

a = [x.strip() for x in f]

Explnation: rstrip() only trims the whitespaces on the right side, what you need is strip() method which strips whitespaces on both sides.

nehem
  • 12,775
  • 6
  • 58
  • 84