A blog reader wrote in to present me with a devious problem. the mdlnam
function returns dynamic model name for generators, excitation systems and
others. Can you spot the problem with the code below?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
In case it isn’t clear. The print
statement prints GENROE
, so we’re
expecting the next output to be bus 100 uses a GENROE model
. However, and
this is where it becomes mysterious, the first if
statement doesn’t
match, nothing matches and instead the else
clause No match
is printed.
What is going on?
mdlname
doesn’t return a user written model name in this example. We know, because
the first print
shows GENROE
. What would you suggest to check next?
Is PSSE returning something that isn’t a string?
I asked the engineer to discover the result of:
1 2 3 4 5 |
|
But this is just a string (<type 'str'>
), so there aren’t any custom data
types being returned.
What does the string really look like?
Finally, I asked what the actual string looked like. To do that use the repr
function. It returns the canonical string representation of the object.
1 2 3 4 5 |
|
Can you see the extra spaces inside the string? That is why the comparison
doesn’t work. 'GENROE ' != 'GENROE'
. The two strings aren’t equal.
Here’s how to fix it:
1 2 3 4 5 6 7 8 |
|
Use the strip
method of the string:
strip()
Return a copy of the string with leading and trailing whitespace removed.
Whenever you are dealing with data, make sure you check it carefully. You may just avoid a headache.