0

I am building a string with this method. But for some reason I am getting the following error

ValueError: unsupported format character ''' (0x27) at index 38

I have no idea where this is coming from. I checked for typos but nothing.

s = "SELECT %s FROM %s "
data = [colName, tableName]

if whereRoughly:
    s+= "(WHERE "
        for i in range(len(whereRoughly[0])):
            s += "%s LIKE '%%s%' "
            if i+1 < len(whereRoughly[0]): s += "OR "
            data.append(whereRoughly[0][i])
            data.append(whereRoughly[1])
     s+= ")"

s += "ORDER BY %s;"
data.append("desc")

print s
print data
print s % tuple(data)

Here I call all the upper code

s.makeSelect(tableName="students", whereRoughly=([1,2], "Wes"))

This is the actual output

SELECT %s FROM %s (WHERE %s LIKE '%%s%' OR %s LIKE '%%s%' )ORDER BY %s;
['*', 'students', 1, 'Wes', 2, 'Wes', 'desc']
1
  • 1
    Also, you really, really shouldn't use += on strings in python. You should properly use combinations of format and join. Commented May 1, 2014 at 14:34

1 Answer 1

1

The problem is here:

"'%%s%'"

There's no format code %', and trying to use it causes an error.

>>> "'%%s%'" % "foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unsupported format character ''' (0x27) at index 5

I assume that you're trying to get the SQL LIKE syntax like '%foo%' (enclosed on either side by % and a single quote.

To get that formatting using the old-style % formatting in Python, you need to escape the leading and trailing percents like this:

>>> "'%%%s%%'" % "foo"
"'%foo%'"

(See the docs.)

This is cleaner with modern-style string.format:

>>> "'%{0}%'".format('foo')
"'%foo%'"

(also, the comment above about not using += to build strings is a valid one -- prefer format and join).

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.