Python percent symbol in string

Python String formatting — percentage symbol after string substituion

The %s works when I don’t add a % within the single quotes immediately, but breaks when I add a % after that even with escaping. Is there a remedy for this, I can’t subsitute variables within an SQL query without this.

@Sreekiran’s answer is the best way to do it. If you really want to stick to your initial string formatting method, you need to do %s%% to get the % sign

@sysuser — if you are using python3.6 then you can use f-string also like query = f»select * from employees where employee_name like ‘%%'»

3 Answers 3

And this is how an SQL injection vulnerability is born. An SQL injection will let an intruder read private data, or even maybe modify data. Never ever pass a raw string into SQL query, unless you have made sure that it has no special characters such as ‘ , % , and \ . Actually, better to use a well tested function that does it for you.

query = "select * from employees where employee_name like '%s%%'" % (name) # (two `%%` at the end) 

solves your problems, but if somehow name == «%’ or » like ‘» (or something of the sort), then suddenly the query becomes:

"select * from employees where employee_name like '%' or '' like '%'" 

which will match all employees. Worse, even name = » is a nightmare in your case. I don’t think that using like in such queries is a good idea, to begin with.

For some information regarding formatting safely you can read stack-overflow questions under the sql-injection tag, such as Protecting against SQL injection in python. Every database system provides its own stored-procedure interface, please use it.

While your question in general is asking about the proper way to format a string in python, for your specific use case (this being a sql query), you should ensure that you are properly escaping your strings.

Читайте также:  Image method in java

This is important for (1) stopping sql injection attacks, and (2) it is also helpful for when your variable-string has a quote in it.

For example, your current query will error for anyone with the name of O’Conner .

Instead, make use of your library’s parametrize methods for doing a query.

You don’t say which sql library you’re using, so I’ll give you an example with MySQLdb.

1) Basic example (without ‘%’ wildcard):

name = "O'Conner" query = ( "SELECT *" " FROM employees" " WHERE employee_name = %s" # notice the lack of quotes around %s ) params = (name,) cursor.execute(query, params) 

2) Since you’re using wildcards, you need to be more explicit:

query = ( "SELECT *" " FROM employees" " WHERE employee_name LIKE '<>%'" # must specify the quotes "".format( MySQLdb.escape_string(name).replace('%', '\\%').replace('_', '\\_') ) ) cursor.execute(query) 

(When you supply a params argument to cursor.execute , it is using MySQLdb.escape_string , behind the scenes. It also handles wrapping with quotes. Note that %s in case 1 is not a typical python %s, as opposed to case 2 — read the docs in the above link for more info.)

Источник

Python print percent sign

💡 Outline

To print percentage sign in Python, we can escape using the percentage sign twice instead of once.

See the code below:

Introduction

In this tutorial, we will see how to print percentage sign in python.

The modulus operator ( % ) or the percentage sign has multiple usages in Python. We use this operator to calculate the remainder for the division between two values for the arithmetic purpose.

We can also use the percentage sign for various string operations. We use it in string formatting and replacing values using format specifiers.

In the above example, we first find the remainder of 10 divided by 3 and store it in a variable a . Then, we have an integer in the print() function, which we display using the %d format specifier. There are different specifiers for different formats. The %s indicates a string, %f indicates float value, and more.

Now we may think about what issue might arise while printing the percentage sign. If we print it normally, there seems to be no problem.

However, we get an error if we aim to print the percent sign ( % ) while using format specifiers.

In the above example, we can see that we wish to print 95.68% using the %s format specifier to provide the value from the string variable val in the print() function. We need to escape the percent sign to display it selectively.

Now let us understand how to escape percent sign in Python.

Using %% Character to Escape Percent Sign in Python

To print percentage sign, we can escape using the percentage sign twice instead of once.

Читайте также:  Nginx php error page

By using the percentage sign twice ( %% ), we can overcome the error. However, if we are not using any specifier, this will print the percentage sign twice only.

Using the format() Function

The format() function can help us to format complex strings with ease. To escape the percent sign, we can place the string variable within curly braces and display the sign separately.

Using the f-String

The f-strings are a new addition to Python 3.6 and up and allow us to format strings faster and more efficiently. The format will be the same as discussed in the previous method.

In this article, we demonstrate the use and function of the percentage sign in Python. With the help of examples, we can understand the errors associated with printing the percent sign and how to overcome them. We also understand a little about string formatting, which is an essential technique in Python to get the result in our desired format.

Was this post helpful?

You may also like:

Bash Get Output from Python Script

Count Unique Values in NumPy Array

Create Array of Arrays in Python

Convert String List to Integer List in Python

Convert Object to Float in Pandas

NameError: Name requests Is Not Defined

Python Hex to String

NameError: Name xrange Is Not Defined in Python

Call Python Script from Bash with Arguments

TypeError: ‘dict_values’ Object Is Not Subscriptable

Share this

Author

Bash get output from python script

Bash Get Output from Python Script

Table of ContentsUsing Substitution SyntaxUsing BackticksUsing PipeUse Pipe with read CommandUse Pipe with tee CommandUsing Redirection Operator Using Substitution Syntax Use Substitution Syntax ($(. )) to get output from a Python script and store it in a Bash variable. [crayon-64c37134dc24c221015188/] [crayon-64c37134dc253638860957/] [crayon-64c37134dc254679036673/] We used the command substitution syntax,$(command), to capture the output of the Python script […]

Count unique values in numpy array

Count Unique Values in NumPy Array

Table of ContentsUse np.unique() method to display unique valuesUse np.unique() method with len() functionUse np.unique() Method with return_counts as true Use np.unique() method to display unique values Use np.unique() to display unique values in numpy array. [crayon-64c37134dc613428358382/] Running the above code will display the following output on the console: [crayon-64c37134dc619656076501/] np.unique() method finds unique values […]

Create array of arrays in Python

Create Array of Arrays in Python

Table of ContentsUse numpy.array() FunctionManually create array of arraysUse numpy.append() Function Use numpy.array() Function To create an array of the arrays in Python: Use the np.array() function to create a numpy.ndarray type array of the arrays. [crayon-64c37134dc7cf888070841/] [crayon-64c37134dc7d4065131018/] The Python library NumPy scientifically computes advanced numerical work. It is a language extension that adds support […]

Convert String List to Integer List in Python

Convert String List to Integer List in Python

Table of ContentsUsing map() MethodUsing for LoopUsing List ComprehensionUsing eval() and ast.literal_eval() MethodsUsing User-defined Function Using map() Method Use the map() method with list() method to convert string list to integer list in Python. [crayon-64c37134d440f532378551/] [crayon-64c37134d4416834047374/] First, we defined a variable named string_list and set its value to a list having five string values. Next, […]

Читайте также:  Прозрачный фон меню css

Convert Object to Float in Pandas

Convert Object to Float in Pandas

Table of ContentsUsing astype() MethodUsing to_numeric() Method Using astype() Method Use the astype() method to convert one DataFrame column from object to float in pandas. [crayon-64c37134dc981127503474/] [crayon-64c37134dc985613659535/] Use the astype() method to convert multiple DataFrame s from object to float in pandas. [crayon-64c37134dc987302382693/] [crayon-64c37134dc989566619051/] Use the astype() method to convert the entire DataFrame from object […]

NameError name requests is not defined

NameError: Name requests Is Not Defined

Table of ContentsReproducing NameError in PythonPossible Solutions to Fix NameError in PythonSolution 1: pip Module InstallationInstall pip using Python 3Check Your import StatementSolution 2: requests Module is Out of Nested ScopeSolution 3: requests Module Imported into the Global Python has a name error when you try to use a variable or function that is not […]

Источник

Python string formatting with percent sign

but it is syntax error. What would be the proper way of doing this without indexing like the first example?

it’s arguable whether it’s more «pythonic» but str.format would allow you to use *args expansion since it’s a method call

3 Answers 3

str % .. accepts a tuple as a right-hand operand, so you can do the following:

>>> x = (1, 2) >>> y = 'hello' >>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')` '1,2,hello' 

Your try should work in Python 3, where Additional Unpacking Generalizations is supported, but not in Python 2.x:

Actuall the extended iterable unpacking does not allow that syntax (python3.4): >>> ‘%d,%d,%s’ % (*x, y) File «», line 1 SyntaxError: can use starred expression only as assignment target Maybe it’ll be allowed by python3.5’s Additional Unpacking Generalizations

>>> x = (5,7) >>> template = 'first: <>, second: <>' >>> template.format(*x) 'first: 5, second: 7' 

Update:

For completeness I am also including additional unpacking generalizations described by PEP 448. The extended syntax was introduced in Python 3.5, and the following is no longer a syntax error:

>>> x = (5, 7) >>> y = 42 >>> template = 'first: <>, second: <>, last: <>' >>> template.format(*x, y) # valid in Python3.5+ 'first: 5, second: 7, last: 42' 

In Python 3.4 and below, however, if you want to pass additional arguments after the unpacked tuple, you are probably best off to pass them as named arguments:

>>> x = (5, 7) >>> y = 42 >>> template = 'first: <>, second: <>, last: ' >>> template.format(*x, last=y) 'first: 5, second: 7, last: 42' 

This avoids the need to build a new tuple containing one extra element at the end.

Источник

Оцените статью