Python newbie question re Strings and integers
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Sat Sep 20 12:54:37 EDT 2008
rmac a écrit :
>
> the following code attempts to extract a symbol name from a string:
> extensionStart = int(filename.rfind('.'))
rfind returns an int, so passing it to the int type constructor is useless.
> filenameStart = int(filename.rfind('/'))
idem
> #print 'Extension Start - ' + str(extensionStart)
The print statement isn't restricted to string objects. And FWIW, you
can use string formating. The above should be either
print "Extension start - ", extensionStart
or
print "Extension start - %s" % extensionStart
As a side not, the naming convention in Python is to use all_lower for
identifiers.
> #print 'FileName Start - ' + str(filenameStart)
idem.
> currentSymbol=filename[int(filenameStart),int(extensionStart)]
Two more useless int constructor calls.
> Uncommenting the print statements clearly show the values to be
> integers
If by 'the values', you mean objects bound to identifiers
'filenameStart' and 'extensionStart', I fail to see how they could be
anything else...
> (and without the str casts actually provide int+string
> errors)
Indeed. What should be the semantic of expression
'answer is ' + 42
???
> However, executing this code results in...
> opening - /Users/rmac/Documents/Sandbox/data/MarketData/AA.csv
> Traceback (most recent call last):
> File "rHistFileToDB_Equities.py", line 25, in <module>
> currentSymbol=filename[int(filenameStart),int(extensionStart)]
> TypeError: string indices must be integers
the expression:
int(filenameStart),int(extensionStart)
1/ takes the object currently bound to identifier 'filenameStart' and
pass it to the int type constructor
2/ takes the object currently bound to identifier 'extensionStart' and
pass it to the int type constructor
3/ build a tuple (actually, a pair of ints) from the results of the two
above expressions
Then you try to use this tuple as an index on a string. A tuple is not a
legal type for string (or any other sequence) subscripting.
The complete syntax for string subscripting is described in the
FineManual. To make a long story short, it's :
string[start:end:step]
where end and step are optionals.
IOW, the correct syntax here is:
filename[filenameStart:extensionStart]
Now, while this is the correct *syntax*, it's not the correct *idiom*.
There's a module named os.path, which provides the needed service. I
leave it up to you to read the relevant part of the documentation...
More information about the Python-list
mailing list