Meanings of percent sign(%) [duplicate] - python

This question already has answers here:
What does % do to strings in Python?
(4 answers)
Closed 8 years ago.
Can you explain what this python code means.
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
The output for the print is
x 3
y 5
The '3' and '5' are values of '(v.varName, v.x)' I don't get how it knows to print 'x' and 'y' and what other uses are there for '%' other than finding the remainder.

The command
for v in m.getVars():
Assigns the list of all Var objects in model m to variable v.
You can then query various attributes of the individual variables in the list.
For example, to obtain the variable name and solution value for the first variable in list v, you would issue the following command
print v.varName, v.x
You can type help(v) to get a list of all methods on a Var object
As others mentioned % is just place holders
To understand how your code works, inspect the model m

It is a way to simplify strings when contain many variables. In python, as you see, you made a string in your print statement which reflects the variables v.varName and v.x. When a percent sign is used in a string, it will be matched, in order, with the parameters you give it.
There are specific letters used for each TYPE of variable. In your case you used "s" and "g" representing a string and a number. Of course numbers are turned into strings if you are creating a string (like in this case).
Example:
x = 20
y = "hello"
z = "some guy"
resulting_string = "%s, my name is %s. I am %g years old" % (y, z, x)
print resulting_string
The result will be:
hello, my name is some guy. I am 20 years old
Notice that the order in the variables section is what gives the correct ordering.

Related

What is the string format "%g%%" mean in python 3? [duplicate]

This question already has answers here:
How can I selectively escape percent (%) in Python strings?
(6 answers)
Closed 4 years ago.
According to python 3 document, the string formating "%%" means "a perncet sign".
Following code is an example:
"%g%%" % 10.34 == "10.34%"
I am not sure what does this "%g" mean here, I suspect it should have the same meaning
as "%g" in string formating, which is "Shorter one among %f or %e". and "%f" or "%e" means
"floating point real number" or "Exponential notaion, lowercase'e'".
Example of them are:
"%f" % 10.34 == '10.34000'
or
"%e" % 1000 == '1.000000e+03'
Based on this understanding, I tried follwoing code. I treid to formatting x first,
and then directly use formating string "%%", but it does not work.
x = '%g' % 10.34
print(isinstance(x, float)) #this returns false
"%%" % x == "10.34%" # this returns error
I then tried this:
x = float(10.34)
print(isinstance(x, float)) #this returns true
"%%" % x == "10.34%" # this returns error as well
I even tried this:
x = "10.34000"
"%%" % x == "10.34%" # this returns error as well
Anyone know what is going on here with "%%". What its mean, do we have to use "%g%%" together with "%%" in any circumstance?
This is solved, the question comes from the misleading of the book. I made comments here:
Since % introduces a format, there must be some way to specify a literal %; that way is %%.
>>> print("%s%%" % "foo")
foo%
It's analogous to how \\ specifies a literal backslash in a string.

How to add comma in print statement in Python [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print variable and string on same line in Python? [duplicate]
(18 answers)
Closed 5 years ago.
I'm new to python and learning how to code.
I'm printing last element of my list and sum of the list as-
print list[-1],sum
But the output is separated by " " and not separated by ",".
Any idea how to separate it by comma?
I'm using Python 2.7
Include it in quotes, like this:
print str(list[-1]) + "," + str(sum)
Enclosing them in str() is unnecessary if list[-1] and sum are strings.
In general, symbols are interpreted as Python symbols (for example, names like sum are interpreted as variable or function names). So whenever you want to print anything as is, you need to enclose it in quotes, to tell Python to ignore its interpretation as a Python symbol. Hence print "sum" will print the word sum, rather than the value stored in a variable called sum.
You'll have to compose that together into a string. Depending on what version of Python you're using, you could either do:
print "{},{}".format(list[-1], sum)
or
print "%s,%s" % (list[-1], sum)
If you were using Python3.6+, there would be a third option:
print(f"{list[-1]},{sum}")
Use the sep keyword argument:
print(list[-1], sum, sep=',')
You can use str.format() and pass whatever variables you want to get it formatted, for example:
x = 1
z = [1, 2, 3]
y = 'hello'
print '{},{},{}'.format(x, z[-1], y)
# prints: 1,3,hello

Understanding this usage of % in Python to create an RGB color from random numbers [duplicate]

This question already has answers here:
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 6 years ago.
I don't understand how this statement is creating a color in Python. I would really appreciate any clarification. I see that it must be substituting in the random numbers but that is as far as I get.
rgb = ('#%02X%02X%02X' % (random.randint(0,255),random.randint(0,255),random.randint(0,255)))
The use of % is the substitute for the variable. For example, if I have the following code,
name = input('Enter your name')
age = input('How old are you?'
print('Hello, %, you are % years old' % name, age)
exit(0)
the % next to "Hello," would be replaced with the value of the variable "name" (As decided by the "% name" which follows the string.
Enter your name: Harvey
Hello, Harvey, you are 18 years old
In your case, the % would be a series of random numbers, which are used to generate the hex colour.

How to print the variable name [duplicate]

This question already has answers here:
How to retrieve a variable's name in python at runtime?
(9 answers)
Closed 9 years ago.
I've designed a code that calculates the percentage of 'CG' appears in a string; GC_content(DNA).
Now I can use this code so that it prints the the value of the string with the highest GC-content;
print (max((GC_content(DNA1)),(GC_content(DNA2)),(GC_content(DNA3)))).
Now how would I get to print the variable name of this max GC_content?
You can get the max of some tuples:
max_content, max_name = max(
(GC_content(DNA1), "DNA1"),
(GC_content(DNA2), "DNA2"),
(GC_content(DNA3), "DNA3")
)
print(max_name)
If you have many DNA variables you could place them in a list
DNA_list = [DNA1, DNA2, DNA3]
I would coerce them into a dictionary to associate the name with the raw data and result.
DNA_dict = dict([("DNA%i" % i, {'data': DNA, 'GC': GC_Content(DNA)}) for i, DNA in enumerate(DNA_list)])
Then list comprehension to get the data you want
name = max([(DNA_dict[key]['GC'], key) for key in DNA_dict])[1]
This has the benefit of allowing variable list length
You seem to want
max([DNA1, DNA2, DNA3], key=GC_content)
It's not what you asked for but it seems to be what you need.

Python print list of sets without brackets [duplicate]

This question already has answers here:
Removing set identifier when printing sets in Python
(5 answers)
Closed 9 years ago.
I have a list of sets (using Python).
Is there a way to print this without the "set([])" stuff around it and just output the actual values they are holding?
Right now I'm getting somthing like this for each item in the list
set(['blah', 'blahh' blahhh')]
And I want it to look more like this
blah,blahh,blahhh
Lots of ways, but the one that occurred to me first is:
s = set([0,1])
", ".join(str(e) for e in s)
Convert everything in the set to a string, and join them together with commas. Obviously your preference for display may vary, but you can happily pass this to print. Should work in python 2 and python 3.
For list of sets:
l = [{0,1}, {2,3}]
for s in l:
print(", ".join(str(e) for e in s))
I'm assuming you want a string representation of the elements in your set. In that case, this should work:
s = set([1,2,3])
print " ".join(str(x) for x in s)
However, this is dependent on the elements of s having a __str__ method, so keep that in mind when printing out elements in your set.
Assuming that your list of sets is called set_list, you can use the following code
for s in set_list:
print ', '.join(str(item) for item in s)
If set_list is equal to [{1,2,3}, {4,5,6}], then the output will be
1, 2, 3
4, 5, 6

Categories