0

I am using Python to create an excel file from a csv file. I am trying to get it to where if the data for the cell begins with a "=" then print it as a function in excel... but i'm not having any luck. I tried to perform a regex on the string to see if it starts with a "=" but it isn't working. Here is what I have so far in Python:

import xlwt
import re

string = '=HYPERLINK("http://www.google.com";"Google")'

if re.match("^=", string) == True:
    formData = re.sub('=', '', string)
    sheet.write(row_count,col-1, Formula("'" + formDta + "'"),style)

Is this not the right approach, or am I just have the wrong syntax? Any suggestions on how I can make this work?

3 Answers 3

1

You don't really need regex for this. Something like: if string.startswith('='): do something would be fine.

That said, here's an excerpt from the Python documentation for the re module:

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).

Which is to say that if you're using re.match(), the ^ start-of-line anchor is not necessary.

EDIT: @aix is correct about the behaviour of re.match() - it will only match the pattern to an entire line (not part thereof.)

Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that you're comparing against True. Python's True is a boolean object. re.match() returns a match object. When Python compares the two, the types don't match, and the if test fails.

The idiomatic way to do a regexp test in python is with:

if re.match(regexp, string):

Python treats most non-False, non-None values as true, for the purposes of if and while tests. The above code uses that behavior - if the regex matches, a match object is returned and the test passes. If the regex does not match, None is returned and the test fails.

Comments

0
s = '=HYPERLINK("http://www.google.com";"Google")'

if s.startswith('='):
   ...

The reason your code doesn't work is that re.match() only returns True if the entire input string matches the regex. In your case, only the first character does. You could either use re.search(), or change the regex to "^=.*". However, I think that startswith() is a better approach.

P.S. I've renamed your variable so that it doesn't shadow the standard string module.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.