string character count
Jean-Michel Pichavant
jeanmichel at sequans.com
Wed Jul 1 06:33:43 EDT 2009
MRAB wrote:
> noydb wrote:
>> If I have a string for a file name such that I want to find the number
>> of characters to the left of the dot, how can that be done?
>>
>> I did it this way:
>> x = "text12345.txt"
>> dot = x.find('.')
>> print dot
>>
>> Was curious to see what method others would use - helps me learn. I
>> guess I was most curious to see if it could be done in one line.
>>
> >>> print "text12345.txt".find('.')
> 9
>
>> And, how would a char count be done with no dot -- like if the string
>> were "textstringwithoutdot" or "no dot in text string"?
>
> If there's no dot then find() returns -1.
>
> If you wanted to know the number of characters before the dot, if
> present, or in total otherwise, then you could use split():
>
> >>> len("text12345.txt".split(".", 1)[0])
> 9
> >>> len("textstringwithoutdot".split(".", 1)[0])
> 20
>
You may have problems with files containing multiple dots.
the os module provide nice & safe methods to parse a file path (on any
system, mac os windows, linux).
>>>f = "/dir1/dir2/test.log"
>>>os.path.splitext(f)
('/dir1/dir2/test', '.log')
>>>os.path.splitext(os.path.basename(f))
('test', '.log')
>>>f2 = 'test.log'
>>>os.path.splitext(os.path.basename(f2))
('test', '.log')
one safe way would be then
>>> import os
>>> x = "text12345.txt"
>>> base , ext = os.path.splitext(os.path.basename(x))
>>> print len(base)
9
Jean-Michel
More information about the Python-list
mailing list