【问题标题】:How to find a part of string in another string?如何在另一个字符串中找到字符串的一部分?
【发布时间】:2013-04-22 06:29:00
【问题描述】:

我需要从文件中读取数据。

f=open("essay.txt","r")
my_string=f.read()

以下以\nSubject: 开头并以\n 结尾的字符串在my_string

Example:
"\nSubject: Good morning - How are you?\n"

如何搜索以 \nSubject: 开头并以 \n 结尾的字符串? 是否有任何 python 函数来搜索字符串的特定模式?

【问题讨论】:

    标签: python string python-2.7 split


    【解决方案1】:

    最好只逐行搜索文件,而不是使用.read() 将其全部加载到内存中。每行以\n 结尾,没有行以它开头:

    with open("essay.txt") as f:
        for line in f:
            if line.startswith('Subject:'):
                pass
    

    在该字符串中搜索它:

    import re
    text = "\nSubject: Good morning - How are you?\n"
    m = re.search(r'\nSubject:.+\n', text)
    if m:
        line = m.group()
    

    【讨论】:

    • 我的问题是在 my_string 中搜索一个以 Subject 开头并以 \n 结尾的字符串
    【解决方案2】:

    试试startswith()。

    str = "Subject: Good morning - How are you?\n"
    
    if str.startswith("Subject"):
        print "Starts with it."
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-28
      相关资源
      最近更新 更多