473,395 Members | 2,253 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

String Formatting

Hi there:

I was wondering if its at all possible to search through a string for a
specific character.

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.

Any help would be appreciated

Aug 10 '06 #1
7 1612
On Thu, 10 Aug 2006 05:35:26 -0700, OriginalBrownster wrote:
Hi there:

I was wondering if its at all possible to search through a string for a
specific character.

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.

Any help would be appreciated
>>s='bread, butter, milk'
s.rsplit(',', 1)[-1]
' milk'
>>s.rsplit(',', 1)[-1].strip()
'milk'
Hope that helps.

Aug 10 '06 #2
OriginalBrownster wrote:
Hi there:

I was wondering if its at all possible to search through a string for a
specific character.

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.

Any help would be appreciated


Would that work for you ?
>>a = 'bread, butter, milk'
a
'bread, butter, milk'
>>b = a.split(',')
b
['bread', ' butter', ' milk']
>>c = b[-1]
c
' milk'
>>d = c.strip()
d
'milk'


HIH
Avell

Aug 10 '06 #3
OriginalBrownster wrote:
Hi there:

I was wondering if its at all possible to search through a string for a
specific character.

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.

Any help would be appreciated
The rfind() method of strings will search through a string for the
first occurance of a substring, starting from the end. (find() starts
from the beginning.)

|>s = "bread, butter, milk"
|>s.rfind(',')
13
|>s.rfind('!')
-1
|>s[s.rfind(',') + 1:]
' milk'

If you want to find either a period or comma you could do it like this:

|>i = max(s.rfind(ch) for ch in ',.')
|>i
13
|>s[i + 1:]
' milk'

Here's the output of help(s.rfind):
Help on built-in function rfind:

rfind(...)
S.rfind(sub [,start [,end]]) -int

Return the highest index in S where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.
Enjoy
Peace,
~Simon

Aug 10 '06 #4

OriginalBrownster wrote:
<snip>
Example

If i had a list: bread, butter, milk
def get_word(s, which=1, sep=','):
return s.split(sep)[which-1].strip()
>>>
get_word('bread, butter, milk')
'milk'
>>>
Aug 10 '06 #5

alisonken1 wrote:
OriginalBrownster wrote:
<snip>
Example

sorry, forgot the '... everything after the last comma ...' part.

Aug 10 '06 #6
Sorry, missed an option in there:
def get_word(s, which=1, sep=','):
return s.split(sep)[which-1].strip()
>>
get_word('bread, butter, milk')
'milk'
>>
>>get_word('bread, butter, milk')
'bread'
>>get_word('bread, butter, milk', 3)
'milk'
>>get_word('bread is brown, butter is yellow, milk is white')
'bread is brown'
>>get_word('bread is brown, butter is yello, milk is white', 3)
'milk is white'

Aug 10 '06 #7
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

Aug 10 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Thomas Philips | last post by:
Consider the following simple dictionary e={1:'one', 2: 'two'} e >>>'one' However, If I attempt to print e using a formatted string print " %(1)s" %e, I get a KeyError: '1'
10
by: Oliver S. | last post by:
I've developed a string-class that holds the string in an array which is a member-variable of the class and that has maximum-size which is con- figurable through a template-parameter. If any...
20
by: hagai26 | last post by:
I am looking for the best and efficient way to replace the first word in a str, like this: "aa to become" -> "/aa/ to become" I know I can use spilt and than join them but I can also use regular...
5
by: Andrew Connell | last post by:
Having fits transforming an XML string using an XSL file. In the 1.1 version of the framework, I see that the XmlResolver is heavily used in the XslTransform class. However, that looks like I am...
4
by: Dennis Myrén | last post by:
Hi. Is there a way to utilize the great primitive data type formatting routines available in .NET without working with strings? I want a byte directly rather than a string. I think it is...
7
by: ilona | last post by:
Hi all, I store phone numbers in the database as 123447775665554(input mask is used for input, and some numbers have extensions), and I also know from db if the number is Canadian, US, or some...
7
by: L. Scott M. | last post by:
Have a quick simple question: dim x as string x = "1234567890" ------------------------------------------------------- VB 6 dim y as string
14
by: Scott M. | last post by:
Ok, this is driving me nuts... I am using VS.NET 2003 and trying to take an item out of a row in a loosely-typed dataset and place it in a label as a currency. As it is now, I am getting my...
1
by: schoedl | last post by:
Hello, we often compose strings via a ostringstream and then create a string from it. What is the rationale of not being able to use string in place of a ostringstream, so I could write ...
6
by: Jack | last post by:
Hi there, Given a standard .NET string, does anyone know what the regular expression would be to locate each (optional) formatting item in the string (or more likely does anyone have a link that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.