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
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
Alternatively, as of Python 2.6, you can use new string formatting (described in PEP 3101):
'Print percent % in sentence and not {0}'.format(test)
which is especially handy as your strings get more complicated.
try using %% to print % sign .
You can't selectively escape %, as % always has a special meaning depending on the following character.
In the documentation of Python, at the bottem of the second table in that section, it states:
'%' No argument is converted, results in a '%' character in the result.
Therefore you should use:
selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
(please note the expicit change to tuple as argument to %)
Without knowing about the above, I would have done:
selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
with the knowledge you obviously already had.
If you are using Python 3.6 or newer, you can use f-string:
>>> test = "have it break."
>>> selectiveEscape = f"Print percent % in sentence and not {test}"
>>> print(selectiveEscape)
... Print percent % in sentence and not have it break.
If the formatting template was read from a file, and you cannot ensure the content doubles the percent sign, then you probably have to detect the percent character and decide programmatically whether it is the start of a placeholder or not. Then the parser should also recognize sequences like %d (and other letters that can be used), but also %(xxx)s etc.
Similar problem can be observed with the new formats -- the text can contain curly braces.
Related
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
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
Alternatively, as of Python 2.6, you can use new string formatting (described in PEP 3101):
'Print percent % in sentence and not {0}'.format(test)
which is especially handy as your strings get more complicated.
try using %% to print % sign .
You can't selectively escape %, as % always has a special meaning depending on the following character.
In the documentation of Python, at the bottem of the second table in that section, it states:
'%' No argument is converted, results in a '%' character in the result.
Therefore you should use:
selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
(please note the expicit change to tuple as argument to %)
Without knowing about the above, I would have done:
selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
with the knowledge you obviously already had.
If you are using Python 3.6 or newer, you can use f-string:
>>> test = "have it break."
>>> selectiveEscape = f"Print percent % in sentence and not {test}"
>>> print(selectiveEscape)
... Print percent % in sentence and not have it break.
If the formatting template was read from a file, and you cannot ensure the content doubles the percent sign, then you probably have to detect the percent character and decide programmatically whether it is the start of a placeholder or not. Then the parser should also recognize sequences like %d (and other letters that can be used), but also %(xxx)s etc.
Similar problem can be observed with the new formats -- the text can contain curly braces.
I have recently started to learn Python and I am hoping that you will be able to help me with a question that has been bothering me. I have been learning Python online with Learn Python The Hard Way. In Exercise 6, I came across a problem where I was using the %r string formatting operation and it was resulting in two different strings. When I printed one string, I got the string with the single quotes (' '). With another I was getting double quotes (" ").
Here is the code:
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print "I said: %r." % x
print "I also said: %r." % y
The result from the first print statement:
I said: 'There are 10 types of people.'.
The result from the second print statement:
I also said: "Those who know binary and those who don't.".
I want to know why one of the statements had a result with the single quotes (' ') and another with (" ").
]
P.S. I am using Python 2.7.
%r is getting the repr version of the string:
>>> x = 'here'
>>> print repr(x)
'here'
You see, single quotes are what are normally used. In the case of y, however, you have a single quote (apostrophe) inside the string. Well, the repr of an object is often defined so that evaluating it as code is equal to the original object. If Python were to use single quotes, that would result in an error:
>>> x = 'those who don't'
File "<stdin>", line 1
x = 'those who don't'
^
SyntaxError: invalid syntax
so it uses double quotes instead.
Notice this line -> do_not = "don't". There is a single quote in this string, that means that single quote has to be escaped; otherwise where would the interpreter know where a string began and ended? Python knows to use "" to represent this string literal.
If we remove the ', then we can expect a single quote surrounding the string:
do_not = "dont"
>>> I also said: 'Those who know binary and those who dont.'.
Single vs. double quotes in python.
My goal with this code is that when you put in a certain number, you will get printed the number and some other output, based on what you typed. For some reason, what I have here gives the error "ValueError: incomplete format". It has something to do with the %. What does the error mean, and how do I fix it? Thanks!
variable = "Blah"
variable2 = "Blahblah"
text = raw_input("Type some stuff: ")
if "1" in text:
print ("One %" % variable)
elif "2" in text:
print ("Two %" % variable2)
Python is expecting another character to follow the % in the string literal to tell it how to represent variable in the resulting string.
Instead use
"One %s" % (variable,)
or
"One {}".format(variable)
to create a new string where the string representation of variable is used instead of the placeholder.
>>> variable = "Blah"
>>> '%s %%' % variable
'Blah %'
>>>
an easy way:
print ("One " + variable)
I have
cmd=arg[3:]
which gives for e.g.
['file python parameter1=5 parameter2=456 ']
When I am printing I want to print in the format - python file parameters..
I tried
print "%s %s %s" % (string.split(cmd[0])[1],string.split(cmd[0])[0],string.split(cmd[0])[2:])
which gives
python file ['parameter1=5 parameter2=456 ']
How can i get the parameters part printed without the square braces or the quotes?
Thanks.
For the last part how can I print
You are asking Python to turn a list into a string. This is why you are seeing the brackets and quotes. All you need to do is use join to make it a string again.
" ".join(string.split(cmd[0])[2:])
or if you really prefer the string module
string.join(" ", string.split(cmd[0])[2:])
I would prefer to see the code written like this if I were doing a code review:
fname, interp, args = cmd[0].split(" ", 2)
print "%s %s %s" % (interp, fname, args)
Use the format method in preference to %-style string formatting.
print "{0[1]} {0[0]} {0[2]}".format(cmd[0].split(None, 2))
You could try something like that:
' '.join(cmd[0].split()[2:])
instead of:
string.split(cmd[0])[2:]
Also, I would recommend you to use an intermediate variable to avoid to do the same split 3 times... Or even better :
print ' '.join(cmd[0].split(' ', 2))
or actually simply:
print cmd[0]
But I guess you don't want to only print it...
What does %s mean in Python? And what does the following bit of code do?
For instance...
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
It is a string formatting syntax (which it borrows from C).
Please see "PyFormat":
Python supports formatting values into
strings. Although this can include
very complicated expressions, the most
basic usage is to insert values into a
string with the %s placeholder.
Here is a really simple example:
#Python 2
name = raw_input("who are you? ")
print "hello %s" % (name,)
#Python 3+
name = input("who are you? ")
print("hello %s" % (name,))
The %s token allows me to insert (and potentially format) a string. Notice that the %s token is replaced by whatever I pass to the string after the % symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.
Andrew's answer is good.
And just to help you out a bit more, here's how you use multiple formatting in one string:
"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".
If you are using ints instead of string, use %d instead of %s.
"My name is %s and I'm %d" % ('john', 12) #My name is john and I'm 12
The format method was introduced in Python 2.6. It is more capable and not much more difficult to use:
>>> "Hello {}, my name is {}".format('john', 'mike')
'Hello john, my name is mike'.
>>> "{1}, {0}".format('world', 'Hello')
'Hello, world'
>>> "{greeting}, {}".format('world', greeting='Hello')
'Hello, world'
>>> '%s' % name
"{'s1': 'hello', 's2': 'sibal'}"
>>> '%s' %name['s1']
'hello'
%sand %d are format specifiers or placeholders for formatting strings, decimals, floats, etc.
The most common used format specifiers:
%s: string
%d: decimals
%f: float
Self explanatory code:
name = "Gandalf"
extendedName = "the Grey"
age = 84
IQ = 149.9
print('type(name): ', type(name)) # type(name): <class 'str'>
print('type(age): ', type(age)) # type(age): <class 'int'>
print('type(IQ): ', type(IQ)) # type(IQ): <class 'float'>
print('%s %s\'s age is %d with incredible IQ of %f ' %(name, extendedName, age, IQ)) # Gandalf the Grey's age is 84 with incredible IQ of 149.900000
# The same output can be printed in following ways:
print ('{0} {1}\'s age is {2} with incredible IQ of {3} '.format(name, extendedName, age, IQ)) # With the help of an older method
print ('{} {}\'s age is {} with incredible IQ of {} '.format(name, extendedName, age, IQ)) # With the help of an older method
print("Multiplication of %d and %f is %f" %(age, IQ, age*IQ)) # Multiplication of 84 and 149.900000 is 12591.600000
# Storing formattings in a string
sub1 = "python string!"
sub2 = "an arg"
a = "I am a %s" % sub1
b = "I am a {0}".format(sub1)
c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)
print(a) # "I am a python string!"
print(b) # "I am a python string!"
print(c) # "with an arg!"
print(d) # "with an arg!"
%s indicates a conversion type of string when using Python's string formatting capabilities. More specifically, %s converts a specified value to a string using the str() function. Compare this with the %r conversion type that uses the repr() function for value conversion.
Take a look at the documentation for string formatting.
To answer your second question: What does this code do?...
This is fairly standard error-checking code for a Python script that accepts command-line arguments.
So the first if statement translates to: if you haven't passed me an argument, I'm going to tell you how you should pass me an argument in the future, e.g. you'll see this on-screen:
Usage: myscript.py database-name
The next if statement checks to see if the 'database-name' you passed to the script actually exists on the filesystem. If not, you'll get a message like this:
ERROR: Database database-name was not found!
From the documentation:
argv[0] is the script name (it is
operating system dependent whether
this is a full pathname or not). If
the command was executed using the -c
command line option to the
interpreter, argv[0] is set to the
string '-c'. If no script name was
passed to the Python interpreter,
argv[0] is the empty string.
Here is a good example in Python 3.
>>> a = input("What is your name? ")
What is your name? Peter
>>> b = input("Where are you from? ")
Where are you from? DE
>>> print("So you are %s of %s." % (a, b))
So you are Peter of DE.