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
Related
This question already has answers here:
How to convert list to string [duplicate]
(3 answers)
Closed 2 years ago.
Here is my list ['k:1','d:2','k:3','z:0'] now I want to remove apostrophes from list item and store it in the string form like 'k:1 , d:2, k:3, z:0' Here is my code
nlist = ['k:1','d:2','k:3','z:0']
newlist = []
for x in nlist:
kk = x.strip("'")
newlist.append(kk)
This code still give me the same thing
Just do this : print(', '.join(['k:1','d:2','k:3','z:0']))
if you want to see them without the apostrophes, try to print one of them alone.
try this:
print(nlist[0])
output: k:1
you can see that apostrophes because it's inside a list, when you call the value alone the text comes clean.
I would recommend studying more about strings, it's very fundamental to know how they work.
The parenthesis comes from the way of representing a list, to know wether an element is a string or not, quotes are used
print(['aStr', False, 5]) # ['aStr', False, 5]
To pass from ['k:1','d:2','k:3','z:0'] to k:1 , d:2, k:3, z:0 you need to join the elements.
values = ['k:1','d:2','k:3','z:0']
value = ", ".join(values)
print(value) # k:1, d:2, k:3, z:0
What you have is a list of strings and you want to join them into a single string.
This can be done with ", ".join(['k:1','d:2','k:3','z:0']).
This question already has an answer here:
How to pad numbers with variable substitution for padding width in format or f string? [duplicate]
(1 answer)
Closed 7 months ago.
I am wondering whether I can add a variable inside the f string to specify the width of item to be printed.
For example:
print("{:>5}".format("cat"))
In the example how can I replace 5 with a variable that can change at runtime.
inside the f string
Be careful using the term "f string" -- you're talking about a format string whereas an f-string is a feature of the latest releases of Python and something different, but related:
animal = 'cat'
pad = 5
print(f"{animal:>{pad}}")
Otherwise, if you just want a format string without the f-string, then #JohnnyMopp's comment (+1) shows the correct syntax.
Here is how:
a = 5
print("{:>"f"{a}""}".format("cat"))
Output:
cat
You can also do that using str.rjust():
a = 5
print("cat".rjust(a))
Output:
cat
This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Print in one line dynamically [duplicate]
(22 answers)
Closed 3 years ago.
I have a program that has to only print data onto one line.
What can I do to do this.
for i in range(10):
print(i)
Is it possible to print all of this on one line so it prints 0, erases the line, print 2, erases, etc..?
Use print(i,end="\r") to return to the start of the line and overwrite.
for i in range(10):
print(i,end=" ")
this is easiest way to print in one line.
in python 2.x:
from __future__ import print_function
for i in range(10):
print (i, end="")
in python 3.x
for i in range(10):
print (i, end="")
For this specific usecase you can do something like this:
print(*range(10))
And to update each character on the line you will need to use '\r' or the return character, that returns the position of the cursor to the beginning of the line. However, you need to be sure you count in the length of the strings you are printing, otherwise you will be overwriting only part of the string. A full proof solution will be:
import time
maxlen = 0
for i in range(12,-1,-1):
if len(str(i))>maxlen:
maxlen = len(str(i))
print(f'\r{str(i): <{maxlen}}',end = '')
time.sleep(2)
print('')
time part is added so that you can view the change. maxlen computes the maximum length string you are going to print and formats the string accordingly. Note: I have used f'strings, hence it would only work for Python 3.x
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.
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