只有在找到我需要的部分时才读取字符串中的字符? [蟒蛇]

时间:2013-12-14 00:03:16

标签: python

我尽可能地表达了标题。基本上,这是我的情景:

我需要读取字符串,而不是文件。在这个字符串中,我想检查这个文件中是否有某段文字。如果在字符串中找到此文本,我想读取此文本,直到我想停止。更具体地说,我从网页获取文本并将其存储在字符串中。在本文中,有一个用户被给出的ID。我想检查ID给出的文本。如果我在字符串中找到这个文本,我想继续阅读,直到我得到实际的ID,然后我需要停止阅读。是的,我可以自己手动读取ID,说实话它可能是一个更好的解决方案,但我想要有一些乐趣,看看这样的事情是如何完成的,如果它可以完成的话。这是我的代码:

        if 'Your ID is: ' in str(response):
            print 'Found ID!'

            # I'd probably have something here to store the ID in a variable for later use.
            # I need to be able to check for the ID after I check for the text 'Your ID is: '. I check for this because I know where to start reading from. I have no way of telling what line the ID could possibly be on.

希望这是有道理的。我只需要检查某段文本是否在字符串中,如果只读取该文本的一小部分,然后将其存储在变量中供以后使用。这可能是一种罕见的情况,我可能永远不会使用它,但看到可能的以及可能的方式永远不会伤害,对吧?

提前致谢!

1 个答案:

答案 0 :(得分:3)

  

我只需要检查某段文本是否在字符串中,如果只读取该文本的一小部分,然后将其存储在变量中供以后使用。

显而易见的事情是使用str.partition

>>> response = 'Hello there. Your ID is: 6. Your name is: Number 6.'
>>> before, matched, after = response.partition('Your ID is: ')
>>> if after:
...     print after
6. Your name is: Number 6.

或者,如果没有找到:

>>> response = 'Hello there. You have no ID. Your name is: Mud.'
>>> before, matched, after = response.partition('Your ID is: ')
>>> if after:
...     print after

那你怎么得到“再多一点”?好吧,你必须决定“多一点”意味着什么,但是很容易切片或splitpartition after变量以获得适当的“小”。也许你想要第一个'.'的所有内容?然后:

>>> response = 'Hello there. Your ID is: 6. Your name is: Number 6.'
>>> before, matched, after = response.partition('Your ID is: ')
>>> if after:
...     yourid, _, _ = after.partition('.')
...     print yourid
6