Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I selectively escape percent (%) in Python strings?

I have the following code

test = "have it break." selectiveEscape = "Print percent % in sentence and not %s" % test  print(selectiveEscape) 

I would like to get the output:

Print percent % in sentence and not have it break. 

What actually happens:

    selectiveEscape = "Use percent % in sentence and not %s" % test TypeError: %d format: a number is required, not str 
like image 681
jondykeman Avatar asked May 21 '12 00:05

jondykeman


People also ask

How do you escape a percent in a string in Python?

Using %% Character to Escape Percent Sign in PythonBy 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.

How do you escape %s in Python?

An escape character is a backslash \ followed by the character you want to insert.

How do you use %s in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.

How do you use a percent string in Python?

The %s signifies that you want to add string value into the string, it is also used to format numbers in a string. After writing the above code (what does %s mean in python), Ones you will print ” string “ then the output will appear as a “ Variable as string = 20 ”.


1 Answers

>>> test = "have it break." >>> selectiveEscape = "Print percent %% in sentence and not %s" % test >>> print selectiveEscape Print percent % in sentence and not have it break. 
like image 126
Nolen Royalty Avatar answered Oct 10 '22 08:10

Nolen Royalty