string character count

nn pruebauno at latinmail.com
Tue Jun 30 16:43:03 EDT 2009


On Jun 30, 1:56 pm, MRAB <pyt... at mrabarnett.plus.com> 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

Also:

len("text12345.txt".partition('.')[0])
9



More information about the Python-list mailing list