Python for Power Systems

A blog for power systems engineers to learn Python.

When a String Isn't a String

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
# get the generator dynamic model name for machine at bus 100.
ierr, genmodel = psspy.mdlnam(100, '1', 'GEN')
print genmodel

if genmodel == 'GENROE':
    print 'bus', 100, 'uses a GENROE model'
elif genmodel == 'GENROU':
    print 'bus', 100, 'uses a GENROU model'
elif genmodel == 'GENSAE':
    print 'bus', 100, 'uses a GENSAE model'
elif genmodel == 'GENSAL':
    print 'bus', 100, 'uses a GENSAL model'
else:
    print 'No match'


# >>>
# GENROE
# No match

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
ierr, genmodel = psspy.mdlnam(100, '1', 'GEN')
print type(genmodel)

# >>>
# <type 'str'>

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
ierr, genmodel = psspy.mdlnam(100, '1', 'GEN')
print repr(genmodel)

# >>>
# 'GENROE      '

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
ierr, genmodel = psspy.mdlnam(100, '1', 'GEN')
genmodel = genmodel.strip()

if genmodel == "GENROE":
    print 'bus', 100, 'uses a GENROE model'

# >>>
# bus 100 uses a GENROE model

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.