Home > Net >  How to get the characters following the keyword from a string (python)?
How to get the characters following the keyword from a string (python)?

Time:05-21

There is a text, for example:

[20:00] User: Error [21:00] User: Auth [21:30] User: Params: first second [22:00] User: ErrorNow

I need to get the "first second" from it, which always come after params. I get the text as a string, it can have several params, I only need the last one in the list.

While the working version looks like this:

par_ind = text.rfind('Params')
text[par_ind:par_ind 13]

But the main disadvantage is that the number of params may change. Tell me a more convenient solution. I was thinking about converting a string into a dictionary, but it seemed like a stupid idea. What else can I look at?

UPD: The full text may look like this:

[20:00] User: Error [21:00] User: Auth [21:30] User: Params: first second [22:00] User: ErrorNow [20:00] User: Error [21:00] User: Auth [21:30] User: Params: first third [22:00] User: ErrorNow [20:00] User: Error [21:00] User: Auth [21:30] User: Params: first fourth [22:00] User: ErrorNow [20:00] User: Error [21:00] User: Auth [21:30] User: Params: first fifth [22:00] User: ErrorNow

I need the last "Params" in the list, in this case "first fifth"

CodePudding user response:

This is a good time to use a regular expression:

>>> import re
>>> text = """[20:00] User: Error [21:00] User: Auth [21:30] User: Params: first second [22:00] User: ErrorNow"""
>>> match = re.search(r'Params: (?P<params>[^[] )\[\d', text)
>>> match.group('params')
'first second '

(You may want to strip the trailing space: match.group('params').strip() can work, or adjust the regular expression accordingly.)

  • Related