Reputation: 1
I am using xlrd to read xls cell into a string, after which none of the string functions work on that string.
attribute_name = str(worksheet.cell_value(row,col))
attribute_name.strip()
attribute_name.lower()
print len(attribute_name)
if(len(attribute_name) > 8):
print 'value' + str(ord(attribute_name[8]))
print 'attributename:'+attribute_name+':'
prints :
9
value32
attributename:TSA01_HE :
9
value32
attributename:TSA02_HE :
I am mainly interested in getting rid of the whitespace at the end of the attribute name. Am I missing anything obvious ? I have tried replace etc but as you can see, even .lower() doesnt work.
$ python --version Python 2.7.5
Upvotes: 0
Views: 66
Reputation: 2822
Take care that both strip()
and lower()
do not modify the string you apply them on; you should therefore do attribute_name = attribute_name.strip().lower()
.
Example:
>>> a = ' A '
>>> a.strip().lower()
'a'
>>> a
' A '
Upvotes: 0
Reputation: 34027
Methods like str.XXX
always return new strings instead of edit the original string. This is because strings are immutables in python. Likewise, operators on string like +=
rebinds the variable to a new string as well:
In [755]: s='a'
In [756]: id(s)
Out[756]: 30887376
In [757]: s+='bc' #same as s=s+'bc'
In [758]: id(s) #identity of the variable has been changed
Out[758]: 301145192
So if you wish your operation on a string to take effect, always remember to assign the result back with =
.
Other immutables like int
s, float
s, tuple
s, frozenset
s works the same as str
s. E.g., you won't expect i=3; i.__add__(10)
makes i==13
.
Upvotes: 2
Reputation: 9904
strip
and lower
do not work in place; they return the changed value. So you should assign their result to the old variable.
attribute_name = attribute_name.strip().lower()
Upvotes: 2