Luke Dinkler
Luke Dinkler

Reputation: 769

How to extract what I want from string in Python

I have a program in Python 3.3 which has a string which I would like to just get the stuff off the end of. For example "Mary had a little lamb". I would like to just get the text after 'a' in the string. How can I do this?

Upvotes: 0

Views: 93

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

s =  "Mary had a little lamb"
print(s.split(" a ")[1])
little lamb
print (s[10:])
little lamb`

Split on the a and get the element after or slice from the 10th char to the end of the string.

s =  'Mary had a very very little lamb'
print(s.split(" a ",1)[1]) 

very very little lamb

If you had one of couple of potential strings:

sts = ["Mary had some little lamb","Mary had a little lamb"]
for s in sts:
    if " a " not  in sts:
        print("a is not in this string so the result is {}".format(s.split("had",1)[1]))
    else:
        print("a is in this string so  the result is {}".format(s.split(" a ",1)[1]))

If you want only the last two words as a string:

sts = ["Mary had some little lamb","Mary had a little lamb"]
for s in sts:
    print(" ".join(s.split()[-2:])) # from second last element to the end
little lamb
little lamb

If you have a string with two " a " and want to split on just the last:

s =  "Mary had a dog and  a little lamb"
print(s.rsplit(" a ",1)[1]) # use rsplit in maxsplit = 1, to only split once
little lamb

If you had complicated search patterns then re would probably be what you need.

Upvotes: 2

Jose Magana
Jose Magana

Reputation: 941

Using the slice method.

result = mystring[start:end]

The start is inclusive, the end is exclusive.

mystring = "Mary had a little lamb"
newstring = mystring[11:]
print(newstring)
>>> "little lamb"

When there isn't a start or end digit that you post, it starts at the very beginning or goes to the very end.

EDIT: Based on your comments from above answer: You could do something like this

>>> mystring = "Mary had a very little lamb"
>>> mystring2 = "Mary had little little lamb"
>>> strings = [mystring, mystring2]
>>> for string in strings:
        if string[9] == 'a':
            newstring = string[11:]
        else:
            newstring2 = string[9:]
>>> newstring
'very little lamb'
>>> newstring2
'little little lamb'

This is assuming there's always a "Mary had.." at the beginning of your string, and will grab what's after the "a" if there is or isn't one. This isn't the best solution I don't think, but gives you a way to think about it.

Upvotes: 1

Related Questions