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.
And, how would a char count be done with no dot -- like if the string
were "textstringwithoutdot" or "no dot in text string"?
> 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
Also:
len("text12345.txt".partition('.')[0])
9
>> >>> len("text12345.txt".split(".", 1)[0])
>> 9
>> >>> len("textstringwithoutdot".split(".", 1)[0])
>> 20
>
> Also:
>
>
>>> len("text.12345.txt".partition('.')[0])
4
>>> len("text.12345.txt".rpartition('.')[0])
10
>>>
unless you've got file names like text.12345.txt, where you might prefer
rpartition.
>>> len("text.12345.txt".partition('.')[0])
4
>>> len("text.12345.txt".rpartition('.')[0])
10
>>>
Emile
>> >>> len("text12345.txt".split(".", 1)[0])
>> 9
>> >>> len("textstringwithoutdot".split(".", 1)[0])
>> 20
>
> Also:
>
>
import os
root, ext = os.path.splitext(x)
print len(root)
or in one line (assuming you've imported os):
print len(os.path.splitext(x)[0])
Iain
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