string character count

MRAB python at mrabarnett.plus.com
Tue Jun 30 13:56:39 EDT 2009


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




More information about the Python-list mailing list