【问题标题】:How to extract what I want from string in Python如何从 Python 中的字符串中提取我想要的内容
【发布时间】:2014-07-29 20:56:33
【问题描述】:

我有一个 Python 3.3 中的程序,它有一个字符串,我想把它放在末尾。例如“玛丽有一只小羊羔”。我只想在字符串中的“a”之后获取文本。我该怎么做?

【问题讨论】:

    标签: string python-3.3


    【解决方案1】:
    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 可能就是您所需要的。

    【讨论】:

    • 谢谢。但问题是字符串的开头(和字符串的长度)并不总是相同的。例如,有时可能是“玛丽有一只小羊羔”,有时可能是“玛丽有一只非常非常小的羊羔”。
    • 如果有时是“玛丽有一些小羊羔”,有时是“玛丽有一只非常非常小的羊羔”。拆分仍然有效吗?如果是这样怎么办?
    • 你想从中得到什么?
    • 重点是字符串的顺序和长度是随机的。
    • 第二个示例中没有a,那么您希望得到什么输出?
    【解决方案2】:

    使用切片方法。

    result = mystring[start:end]
    

    开始是包容的,结束是排斥的。

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

    当您发布的没有开始或结束数字时,它会从头开始或一直到最后。

    编辑:根据上述答案中的 cmets:你可以做这样的事情

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

    这是假设在你的字符串的开头总是有一个“Mary had..”,如果有或没有,它将抓住“a”之后的内容。这不是我认为的最佳解决方案,但可以让您思考它。

    【讨论】:

    • 这很有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-07-22
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    相关资源
    最近更新 更多