String Formatting

John Machin sjmachin at lexicon.net
Thu Aug 10 19:30:25 EDT 2006


OriginalBrownster wrote:
> Hi there:
>
> I was wondering if its at all possible to search through a string for a
> specific character.

Don't wonder; read the tutorials, read the manuals, and ponder the
sheer uselessness of any computer language that offered neither such a
facility nor the means to build it yourself.

>
> I want to search through a string backwords and find the last
> period/comma, then take everything after that period/comma


>
> Example
>
> If i had a list:    bread, butter, milk
>
> I want to just take that last entry of milk. However the need for it
> arises from something more complicated.
>

Python terminology: that's not a list, it's a string.

> Any help would be appreciated

If you already know that you are looking for a comma, then the
following will do the job. If you know that you are looking for a
period, make the obvious substitution.

>>> x = " bread, butter, milk "
>>> x.split(",")
[' bread', ' butter', ' milk ']
>>> x.split(",")[-1]
' milk '
>>> x.split(",")[-1].strip()
'milk'
>>> x = " no commas at all "
>>> x.split(",")
[' no commas at all ']
>>> x.split(",")[-1]
' no commas at all '
>>> x.split(",")[-1].strip()
'no commas at all'
>>>

*HOWEVER* if you really mean what you said (i.e. start at the
rightmost, go left until you strike either a comma or a period,
whichever comes first) then you need something like this:

>>> def grab_last_chunk(s):
...    return s[max(s.rfind(','), s.rfind('.')) + 1:]
...
>>> grab_last_chunk(" bread, butter, milk ")
' milk '
>>> grab_last_chunk(" bread, butter. milk ")
' milk '
>>> grab_last_chunk(" bread! butter! milk ")
' bread! butter! milk '
>>> grab_last_chunk(" bread, butter, milk.")
''
>>>

The serendipity in the above is that if the sought character is not
found, rfind() returns -1 which fits in nicely without the need for an
"if" statement to do something special.

HTH,
John




More information about the Python-list mailing list