Henry
Henry

Reputation: 67

Change variable between parentheses

this is my code:

for i, line in enumerate(searchlines):
    b = 1.860572
    if "%b" in line and "4.871899" in line and "1.995131" in line:
        m.write("match" + "\n")

I would like to have the b variable in the place where I now have '%b', so its just like the other two numbers, but without hard coding it. Anybody knows how to do this? I'm still learning Python.

Upvotes: 1

Views: 116

Answers (1)

Kevin
Kevin

Reputation: 76194

if str(b) in line and "4.871899" in line and "1.995131" in line:

Incidentally, it is slightly inefficient to have an assignment inside a for loop that doesn't change based on the thing being iterated over. Depending on your use case, it may make more sense to do:

b = 1.860572
for i, line in enumerate(searchlines):
    if str(b) in line and "4.871899" in line and "1.995131" in line:
        m.write("match" + "\n")

Or

b = "1.860572"
for i, line in enumerate(searchlines):
    if b in line and "4.871899" in line and "1.995131" in line:
        m.write("match" + "\n")

Or

b = 1.860572
b_s = str(b)
for i, line in enumerate(searchlines):
    if b_s in line and "4.871899" in line and "1.995131" in line:
        m.write("match" + "\n")

One more thing to watch out for: converting a float to a string doesn't always give you the same literal value you used to create the float in the first place.

>>> b = 1.9999999999999999
>>> s ="1.9999999999999999"
>>> str(b) in s
False
>>> str(b) in "abc2.0def"
True
>>> str(b)
'2.0'

This is because str is designed to return a readable string, not necessarily something perfectly representative of the object's data. For floats, this means str() might round to fewer decimal places than you originally specified. So if you're searching through a file for a precise sequence of digits, it may make sense to create b as a string in the first place, so there's no loss of precision.

Upvotes: 5

Related Questions