如何从Python中提取我想要的字符串

时间:2014-07-29 20:56:34

标签: string python-3.3

我在Python 3.3中有一个程序,它有一个字符串,我想把这些东西放到最后。例如"玛丽有一只小羊羔"。我想在' a'之后得到文字。在字符串中。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

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

a上拆分并获取10th字符之后或切片到字符串末尾的元素。

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

very very little lamb

如果你有两个潜在的字符串之一:

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]))

如果您只想将最后两个单词作为字符串:

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

如果您有一个包含两个" a "的字符串,并且想要仅拆分最后一个字符串:

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

如果你有复杂的搜索模式,那么re可能就是你需要的。

答案 1 :(得分:1)

使用切片方法。

result = mystring[start:end]

开始是包容性的,结束是独家的。

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

如果您没有发布的开始或结束数字,则会从最开始或结束时开始。

编辑:根据你上面的评论答案:你可以做这样的事情

>>> 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'

这是假设总有一个"玛丽有......"在你的字符串的开头,并将抓住" a"之后的内容。如果有或没有。这不是我不会想到的最佳解决方案,但会为您提供一种思考方式。