I have this line of code:
print ("(x %s)(x %s)") % (var_p1, var_p2)
But it does not work, I am new to programming and I don't know what I have done wrong. Any experts out there with a simple answer?
I wanted it to randomly select an equation for a parabola. e.g. (x-3)(x+1) However, it comes up with the error message:
Traceback (most recent call last):
"File "E:/Python34/MyFiles/Math Study Buddy.py", line 26 in <module>
print ("(x %s)(x %s)") % (var_p1, var_p2)
TypeError: unsupported operand type (s) for %: 'NoneType' and 'tuple'
As you are in python 3 you need to put the variables inside the parenthesis after your string:
>>> print ("(x %s)(x %s)"%(2, 3))
(x 2)(x 3)
Note that in python 3 print is a function and you need to pass the string as its argument.So you can not put your variables outside the function!
For more detail read printf-style String Formatting
Note
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.
You can use str.format
>>> var_p1 = 'test'
>>> var_p2 = 'test2'
>>> print(("(x {})(x {})".format(var_p1, var_p2)))
(x test)(x test2)
you don't need to use 'x' to substitude variables here.
This will fix:
print ("(%s)(%s)") % (var_p1, var_p2)
also, .format is better than %
see:
Python string formatting: % vs. .format
Related
I am learning python(2.7) on my own.
I have learned that we can use the following ways to put strings and variables together in printing:
x = "Hello"
y = "World"
By using commas:
print "I am printing" , x, y # I know that using comma gives automatic space
By using concatenation :
print "I am printing" + " " + x + " " + y
By using string formatters
print "I am printing %s %s" % (x, y)
In this case all three print the same:
I am printing Hello World
What is the difference between the three and are there any particular instances where one is preferred over the other?
To answer the general question first, you would use printing in general to output information in your scripts to the screen when you're writing code to ensure that you're getting what you expect.
As your code becomes more sophisticated, you may find that logging would be better than printing, but that's information for another answer.
There is a big difference between printing and the return values' representations that are echoed in an interactive session with the Python interpreter. Printing should print to your standard output. The echoed representation of the expression's return value (that show up in your Python shell if not None) will be silent when running the equivalent code in scripts.
1. Printing
In Python 2, we had print statements. In Python 3, we get a print function, which we can also use in Python 2.
Print Statements with Commas (Python 2)
The print statement with commas separating items, uses a space to separate them. A trailing comma will cause another space to be appended. No trailing comma will append a newline character to be appended to your printed item.
You could put each item on a separate print statement and use a comma after each and they would print the same, on the same line.
For example (this would only work in a script, in an interactive shell, you'd get a new prompt after every line):
x = "Hello"
y = "World"
print "I am printing",
print x,
print y
Would output:
I am printing Hello World
Print Function
With the built-in print function from Python 3, also available in Python 2.6 and 2.7 with this import:
from __future__ import print_function
you can declare a separator and an end, which gives us a lot more flexibility:
>>> print('hello', 'world', sep='-', end='\n****\n')
hello-world
****
>>>
The defaults are ' ' for sep and '\n' for end:
>>> print('hello', 'world')
hello world
>>>
2. String Concatenation
Concatenation creates each string in memory, and then combines them together at their ends in a new string (so this may not be very memory friendly), and then prints them to your output at the same time. This is good when you need to join strings, likely constructed elsewhere, together.
print('hello' + '-' + 'world')
will print
hello-world
Be careful before you attempt to join in this manner literals of other types to strings, to convert the literals to strings first.
print('here is a number: ' + str(2))
prints
here is a number: 2
If you attempt to concatenate the integer without coercing it to a string first:
>>> print('here is a number: ' + 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
This should demonstrate that you should only ever attempt to concatenate variables that are known to be strings. The new way of formatting demonstrated next handles this issue for you.
3. String Interpolation
The formatting you're demonstrating is the old style of string interpolation, borrowed from C. It takes the old string and one time creates a new one. What it does is fairly straightforward. You should use this when you may seem likely to building up a fairly large template (at 3+ lines and 3+ variables, you definitely should be doing it this way).
The new way of doing that would be to do this (using the index of the arguments):
print('I am printing {0} and {1}'.format(x, y))
or in python 2.7 or 3 (using the implied index):
print('I am printing {} and {}'.format(x, y))
or with named arguments (this is semantically easy to read, but the code doesn't look very DRY (i.e. Don't Repeat Yourself))
print('I am printing {x} and {y}'.format(x=x, y=y))
The biggest benefit of this over % style formatting (not demonstrated here) is that it lets you combine positional and keyword arguments
print('I am printing {0} and {y}'.format(x, y=y))
New in Python 3.6, format literals
Python 3.6 will have format literals, with a more elegant syntax (less redundancy). The simple syntax is something like:
print(f'I am printing {x} and {y}')
The format literals can actually execute code in-place:
>>> print(f'I am printing {"hello".capitalize()} and {"Wo" + "rld"}')
I am printing Hello and World
you should build list and use join with delimiter
for example
",".join(list_name)
What are options for keeping as close to the python2 way of printing.
>>> x1='hi'
>>> x2='there'
>>> print "Val1=%s Val2=%s" %(x1,x2)
File "<stdin>", line 1
print "%s" %x
^
SyntaxError: invalid syntax
It would not be necessary to mention : "lose your 'old' way of thinking and use the {} in python3." I am aware of the "blessed" python3 syntax, and given it is not in my estimation preferable, would like to see what other options exist.
thanks.
That is still valid syntax in python 3, but print is no longer a statement. It is a function, so you must put parentheses:
print("%s" % x)
None. Avoid print/print() entirely if you want perfect compatibility.
sys.stdout.write('%s\n' % (x,))
Python 2.7.3
>>> print '%2.2f' % 0.1
0.10
The documentation I have says that type % should be the same as type f except that the input is multiplied by 100.
>>> print '%2.2%' % 0.1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
use the new format expression, which has the formatter you are referring to
print "{:%}".format(0.1)
#10.000000%
if you just want the integer part you can use the precision specification
print "{:.0%}".format(0.1)
#10%
see the doc at
http://docs.python.org/2/library/string#formatspec
To expand a little bit, the new format specificator is really more powerful than the old one. First of all it's really simple calling the parameters by order or name
"play the {instrument} all {moment}, even if my {instrument} is old".format(moment='day', instrument='guitar')
#'play the guitar all day, even if my guitar is old'
then, as can be seen in the documentation, is possible to have access to properties of the object:
"the real component is {0.real} and the imaginary one is {0.imag}".format(3+4j)
#'the real component is 3.0 and the imaginary one is 4.0'
There is a lot more than this, but you can find it all in the documentation, that is very clear.
Came across this question. In Python 3 you can simply use fstrings (thus avoiding the .format) in a similar way as described above. The format is:
print(f"{your_number:.n_decimals%}")
Eg.
>>> print(f"{0.0350:.2%}")
3.50%
print '%2.2%' % 0.1
Tells it that there are 2 placeholders in format string (%), so you have a complain
I'd like to get a few opinions on the best way to replace a substring of a string with some other text. Here's an example:
I have a string, a, which could be something like "Hello my name is $name". I also have another string, b, which I want to insert into string a in the place of its substring '$name'.
I assume it would be easiest if the replaceable variable is indicated some way. I used a dollar sign, but it could be a string between curly braces or whatever you feel would work best.
Solution:
Here's how I decided to do it:
from string import Template
message = 'You replied to $percentageReplied of your message. ' +
'You earned $moneyMade.'
template = Template(message)
print template.safe_substitute(
percentageReplied = '15%',
moneyMade = '$20')
Here are the most common ways to do it:
>>> import string
>>> t = string.Template("Hello my name is $name")
>>> print t.substitute(name='Guido')
Hello my name is Guido
>>> t = "Hello my name is %(name)s"
>>> print t % dict(name='Tim')
Hello my name is Tim
>>> t = "Hello my name is {name}"
>>> print t.format(name='Barry')
Hello my name is Barry
The approach using string.Template is easy to learn and should be familiar to bash users. It is suitable for exposing to end-users. This style became available in Python 2.4.
The percent-style will be familiar to many people coming from other programming languages. Some people find this style to be error-prone because of the trailing "s" in %(name)s, because the %-operator has the same precedence as multiplication, and because the behavior of the applied arguments depends on their data type (tuples and dicts get special handling). This style has been supported in Python since the beginning.
The curly-bracket style is only supported in Python 2.6 or later. It is the most flexible style (providing a rich set of control characters and allowing objects to implement custom formatters).
There are a number of ways to do it, the more commonly used would be through the facilities already provided by strings. That means the use of the % operator, or better yet, the newer and recommended str.format().
Example:
a = "Hello my name is {name}"
result = a.format(name=b)
Or more simply
result = "Hello my name is {name}".format(name=b)
You can also use positional arguments:
result = "Hello my name is {}, says {}".format(name, speaker)
Or with explicit indexes:
result = "Hello my name is {0}, says {1}".format(name, speaker)
Which allows you to change the ordering of the fields in the string without changing the call to format():
result = "{1} says: 'Hello my name is {0}'".format(name, speaker)
Format is really powerful. You can use it to decide how wide to make a field, how to write numbers, and other formatting of the sort, depending on what you write inside the brackets.
You could also use the str.replace() function, or regular expressions (from the re module) if the replacements are more complicated.
Checkout the replace() function in python. Here is a link:
http://www.tutorialspoint.com/python/string_replace.htm
This should be useful when trying to replace some text that you have specified. For example, in the link they show you this:
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
For every word "is", it would replace it with the word "was".
Actually this is already implemented in the module string.Template.
You can do something like:
"My name is {name}".format(name="Name")
It's supported natively in python, as you can see here:
http://www.python.org/dev/peps/pep-3101/
You may also use formatting with % but .format() is considered more modern.
>>> "Your name is %(name)s. age: %(age)i" % {'name' : 'tom', 'age': 3}
'Your name is tom'
but it also supports some type checking as known from usual % formatting:
>>> '%(x)i' % {'x': 'string'}
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
'%(x)i' % {'x': 'string'}
TypeError: %d format: a number is required, not str
I am trying to use a python script to call an external command a number of times, each time with a different variable.
I see there are recommendations to use subprocess.call to do this, however all the documentation I have found doesn't explain how to pass this function variables (from a list for example).
I have tried a number of different formats, and I think a substitution would be the best, but it seems like the function wont accept the variable.
The code I am trying to get working is:
#!/usr/bin/python
domain_list = ["google.com", "google.ie"]
from subprocess import call
for x in domain_list:
print x
cmd_list = ['dig', '+short', '%s'] %x
call(cmd_list, shell=True)
This is failing with:
Traceback (most recent call last):
File "./dnscheck.py", line 16, in <module>
cmd_list = ['dig', '+short', '%s'] %arg
TypeError: unsupported operand type(s) for %: 'list' and 'str'
Really I want to be able to pass a bunch of different domains (defined in a list) to dig and receive the IP's of those domains.
I've just started with python so sorry if this is very basic!
You are trying to use the modulo operator on a list, I presume you wanted to do string formatting on the last item, as the percentage symbol is overloaded to do formatting with strings, but as you just want to insert the item without any formatting, you can just give it directly:
['dig', '+short', x]
If you did want to use formatting, you would need to do it on the string:
['dig', '+short', '%s' % x]
Note however, that this is pointless given you are not doing any formatting.