I think you want this:
if lineMatch:
print(', '.join(['"{}"'.format(t) for t in lineMatch.groups()]))
Usage:
>>> m = re.search('(\d{4})-(\S+)', "1995-jun")
>>> print ', '.join(['"{}"'.format(i) for i in m.groups()])
"1995", "jun"
Domanda
I'm writing a script to parse out lines of interest from a log. It is working well except for printing the lines. I have a parameterized regex that I use in an re.search
, which returns my results. I can print them individually or by looping through the list.
My problem is that for each match, I want to print a CSV line, basically each value in quotes with a comma between (and no comma on the end of the line). Is there an easy way to do this?
I have this:
if lineMatch:
for capturedToken in lineMatch.groups():
#print capturedToken
Using Python 2.7 how would I print as a CSV line (followed by a new line)?
I've tried print/end but from what I understand that is only Python 3.x - every variation I tried gave me syntax errors. I'm sure there's a cool Pythonic way to print the values from the linematch group as a comma separated list; I just don't seem to be able to find it!
Soluzione
I think you want this:
if lineMatch:
print(', '.join(['"{}"'.format(t) for t in lineMatch.groups()]))
Usage:
>>> m = re.search('(\d{4})-(\S+)', "1995-jun")
>>> print ', '.join(['"{}"'.format(i) for i in m.groups()])
"1995", "jun"
Altri suggerimenti
Use join method from strings like this:
print ",".join(lineMatch.groups())