user3092850
user3092850

Reputation: 29

strip out part of a string between reocurring characters using python

Using Python I am currently trying to strip out part of a string that occurs between two characters. The string can be different lengths, so character counting will not work. An example of what I am looking for would be:

172.-.221 - - [07/-20-:16:36:27 -0500] Firefox/17.0" ** 0 s/ 950 ms **

The desired section of the string is 0 s/ 950 ms, and I have noticed that it occurs between the pairs of double asterisks (** **) consistently.

How would I grab just the part of the string between the two double asterisks (**)? How would I either output that to the screen or save that to a file?

Upvotes: 2

Views: 178

Answers (5)

Steve Barnes
Steve Barnes

Reputation: 28390

This is exactly the sort of thing that re is made for. e.g.

import re

TheString = '172.-.221 - - [07/-20-:16:36:27 -0500] Firefox/17.0" ** 0 s/ 950 ms **'

wc = re.compile(r'\*\*(.*)\*\*')
matches = wc.findall(TheString)

#returns ['0 s/ 950 ms ']

Upvotes: 3

GMPrazzoli
GMPrazzoli

Reputation: 239

This is good as well :)

>>> import re
>>> string = '172.-.221 - - [07/-20-:16:36:27 -0500] Firefox/17.0" ** 0 s/ 950 ms **'
>>> re.search('\*{2}(.+)\*{2}', string).group(1)
' 0 s/ 950 ms '

Upvotes: 1

ndpu
ndpu

Reputation: 22561

>>> s='172.-.221 - - [07/-20-:16:36:27 -0500] Firefox/17.0" ** 0 s/ 950 ms **'
>>> s.split('**')[1].strip()
'0 s/ 950 ms'

Upvotes: 2

jonrsharpe
jonrsharpe

Reputation: 122052

You could use str.split to extract it:

myString.split("**")[1]

This creates a list of strings by splitting the string at each appearance of "**", then takes the second item, index 1, from that list.

Upvotes: 1

Ali Rasim Kocal
Ali Rasim Kocal

Reputation: 540

You can use regular expressions (the sub method). Here is a good tutorial by Google: https://developers.google.com/edu/python/regular-expressions

Upvotes: 0

Related Questions