using print with a comma in python 3 [duplicate] - python

This question already has answers here:
Print new output on same line [duplicate]
(7 answers)
Closed 7 years ago.
Using python 3 print(), does not list the repeated data one after the other on the same line?
Let's say you want a message to display on the same line and repeatedly.
example.
my_message = 'Hello'
for i in range(100) :
print(my_message),
it IS CURRENTLY printing one below the other.(not what I want)
hello
hello
hello.....
but I read in the python book that adding a comma , after print(), should create the desired effect and would make it display side by side
hello hello hello hello..(x100)
why doesn't it do that in Python 3? How do you fix it?

This does not work in Python 3 because in Python 3, print is a function. To get the desired affect, use:
myMessage = "Hello"
for i in range(100):
print(myMessage, end=" ")
or more concisely:
print(" ".join("Hello" for _ in range(100)))

Since print() is a function in Python 3, you can pass multiple arguments to it using the *-operator.
You can do this with a tuple:
print(*('Hello' for x in range(100)))
Or with a list (created by a list comprehension):
print(*['Hello' for x in range(100)])
Another way would be to use join():
print(' '.join('Hello' for x in range(100)))
You can also use the end keyword:
for x in range(100):
print('Hello', end=' ')
In Python 2.x this was possible:
for x in xrange(100):
print 'Hello',

In Python 3, simply
print(*('Hello' for _ in range(5)))
There is no need to create a list or to use join.
To have something other than one space between each "Hello", pass the sep argument (note it's keyword-only):
print(*('Hello' for _ in range(5)), sep=', ')
gives you
Hello, Hello, Hello, Hello, Hello

Related

how would i make the outputs appear on the same line (python) [duplicate]

I'm new to python and I'm trying to scan multiple numbers separated by spaces (let's assume '1 2 3' as an example) in a single line and add it to a list of int. I did it by using:
#gets the string
string = input('Input numbers: ')
#converts the string into an array of int, excluding the whitespaces
array = [int(s) for s in string.split()]
Apparently it works, since when I type in '1 2 3' and do a print(array) the output is:
[1, 2, 3]
But I want to print it in a single line without the brackets, and with a space in between the numbers, like this:
1 2 3
I've tried doing:
for i in array:
print(array[i], end=" ")
But I get an error:
2 3 Traceback (most recent call last):
print(array[i], end=" ")
IndexError: list index out of range
How can I print the list of ints (assuming my first two lines of code are right) in a single line, and without the brackets and commas?
Yes that is possible in Python 3, just use * before the variable like:
print(*list)
This will print the list separated by spaces.
(where * is the unpacking operator that turns a list into positional arguments, print(*[1,2,3]) is the same as print(1,2,3), see also What does the star operator mean, in a function call?)
You want to say
for i in array:
print(i, end=" ")
The syntax i in array iterates over each member of the list. So, array[i] was trying to access array[1], array[2], and array[3], but the last of these is out of bounds (array has indices 0, 1, and 2).
You can get the same effect with print(" ".join(map(str,array))).
Try using join on a str conversion of your ints:
print(' '.join(str(x) for x in array))
For python 3.7
these will both work in Python 2.7 and Python 3.x:
>>> l = [1, 2, 3]
>>> print(' '.join(str(x) for x in l))
1 2 3
>>> print(' '.join(map(str, l)))
1 2 3
btw, array is a reserved word in Python.
You have multiple options, each with different general use cases.
The first would be to use a for loop, as you described, but in the following way.
for value in array:
print(value, end=' ')
You could also use str.join for a simple, readable one-liner using comprehension. This method would be good for storing this value to a variable.
print(' '.join(str(value) for value in array))
My favorite method, however, would be to pass array as *args, with a sep of ' '. Note, however, that this method will only produce a printed output, not a value that may be stored to a variable.
print(*array, sep=' ')
If you write
a = [1, 2, 3, 4, 5]
print(*a, sep = ',')
You get this output: 1,2,3,4,5
# Print In One Line Python
print('Enter Value')
n = int(input())
print(*range(1, n+1), sep="")
lstofGroups=[1,2,3,4,5,6,7,8,9,10]
print(*lstofGroups, sep = ',')
don't forget to put * before the List
For python 2.7 another trick is:
arr = [1,2,3]
for num in arr:
print num,
# will print 1 2 3
you can use more elements "end" in print:
for iValue in arr:
print(iValue, end = ", ");
Maybe this code will help you.
>>> def sort(lists):
... lists.sort()
... return lists
...
>>> datalist = [6,3,4,1,3,2,9]
>>> print(*sort(datalist), end=" ")
1 2 3 3 4 6 9
you can use an empty list variable to collect the user input, with method append().
and if you want to print list in one line you can use print(*list)

How to unstring a list/tuple without eval [duplicate]

This question already has answers here:
Convert string to nested structures like list
(2 answers)
Closed 7 years ago.
I'm trying to use input to get the value for a tuple. However, since input sets the value as a string, I'm trying to unstring it as well. I've found that eval works for this purpose, but that it should be distrusted. While this will not be a problem as long as I use the code privately, if I were to publicly release it I want to use the best code possible.
So, is there another way of unstringing a tuple in Python 3?
Here's what I'm currently doing:
>>> a = input("What is the value? ")
What is the value? (3,4)
>>> a
'(3,4)'
>>> eval(a)
(3, 4)
Use the safe version of eval, ast.literal_eval which is designed exactly for what you are trying to achieve:
from ast import literal_eval
tup = literal_eval(a)
I'd do it like this:
>>> inp = input()
'(3,4)'
>>> tuple(map(int, inp.strip()[1:-1].split(',')))
(3, 4)
where strip will make sure leading or trailing blanks won't ruin your day.
Simple, you don't ask the user to input a tuple. Instead you do this:
x = input("Enter x value: ")
y = input("Enter y value: ")
data = (
int(x),
int(y)
)
print(
repr(data)
)
--output:--
(10, 3)

How to use python to print strings as processing like this

I want to write a function to print out string like this:
Found xxxx...
for x is result calculating by another function. It only print one line, sequential, but not one time. Example: I want to print my_name but it'll be m.... and my.... and my_...., at only line.
Can i do this with python?
Sorry I can't explain clearly by english.
UPDATE
Example code;
import requests
url = 'http://example.com/?get='
list = ['black', 'white', 'pink']
def get_num(id):
num = requests.get(url+id).text
return num
def print_out():
for i in list:
num = get_num(i)
if __name__ == '__main__':
#Now at main I want to print out 2... (for example, first get_num value is 2) and after calculating 2nd loop print_out, such as 5, it will update 25...
#But not like this:
#2...
#25...
#25x...
#I want to it update on one line :)
If you are looking to print your output all in the same line, and you are using Python 2.7, you can do a couple of things.
First Method Py2.7
Simply doing this:
# Note the comma at the end
print('stuff'),
Will keep the print on the same line but there will be a space in between
Second Method Py2.7
import sys
sys.stdout.write("stuff")
This will print everything on the same line without a space. Be careful, however, as it only takes type str. If you pass an int you will get an exception.
So, in a code example, to illustrate the usage of both you can do something like this:
import sys
def foo():
data = ["stuff"]
print("Found: "),
for i in data:
sys.stdout.write(i)
#if you want a new line...just print
print("")
foo()
Output:
Found: stuff
Python 3 Info
Just to add extra info about using this in Python 3, you can simply do this instead:
print("stuff", end="")
Output example taken from docs here
>>> for i in range(4):
... print(i, end=" ")
...
0 1 2 3 >>>
>>> for i in range(4):
... print(i, end=" :-) ")
...
0 :-) 1 :-) 2 :-) 3 :-) >>>
s = "my_name"
for letter in range(len(s)):
print("Found",s[0:letter+1])
Instead of 's' you can just call function with your desired return value.

Printing a list separated with commas, without a trailing comma

I am writing a piece of code that should output a list of items separated with a comma. The list is generated with a for loop:
for x in range(5):
print(x, end=",")
The problem is I don't know how to get rid of the last comma that is added with the last entry in the list. It outputs this:
0,1,2,3,4,
How do I remove the ending ,?
Pass sep="," as an argument to print()
You are nearly there with the print statement.
There is no need for a loop, print has a sep parameter as well as end.
>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4
A little explanation
The print builtin takes any number of items as arguments to be printed. Any non-keyword arguments will be printed, separated by sep. The default value for sep is a single space.
>>> print("hello", "world")
hello world
Changing sep has the expected result.
>>> print("hello", "world", sep=" cruel ")
hello cruel world
Each argument is stringified as with str(). Passing an iterable to the print statement will stringify the iterable as one argument.
>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']
However, if you put the asterisk in front of your iterable this decomposes it into separate arguments and allows for the intended use of sep.
>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world
>>> print(*range(5), sep="---")
0---1---2---3---4
Using join as an alternative
The alternative approach for joining an iterable into a string with a given separator is to use the join method of a separator string.
>>>print(" cruel ".join(["hello", "world"]))
hello cruel world
This is slightly clumsier because it requires non-string elements to be explicitly converted to strings.
>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4
Brute force - non-pythonic
The approach you suggest is one where a loop is used to concatenate a string adding commas along the way. Of course this produces the correct result but its much harder work.
>>>iterable = range(5)
>>>result = ""
>>>for item, i in enumerate(iterable):
>>> result = result + str(item)
>>> if i > len(iterable) - 1:
>>> result = result + ","
>>>print(result)
0,1,2,3,4
You can use str.join() and create the string you want to print and then print it. Example -
print(','.join([str(x) for x in range(5)]))
Demo -
>>> print(','.join([str(x) for x in range(5)]))
0,1,2,3,4
I am using list comprehension above, as that is faster than generator expression , when used with str.join .
To do that, you can use str.join().
In [1]: print ','.join(map(str,range(5)))
0,1,2,3,4
We will need to convert the numbers in range(5) to string first to call str.join(). We do that using map() operation. Then we join the list of strings obtained from map() with a comma ,.
Another form you can use, closer to your original code:
opt_comma="" # no comma on first print
for x in range(5):
print (opt_comma,x,sep="",end="") # we are manually handling sep and end
opt_comma="," # use comma for prints after the first one
print() # force new line
Of course, the intent of your program is probably better served by the other, more pythonic answers in this thread. Still, in some situations, this could be a useful method.
Another possibility:
for x in range(5):
if x:
print (", ",x,end="")
else:
print (x, end="")
print()
for n in range(5):
if n == (5-1):
print(n, end='')
else:
print(n, end=',')
An example code:
for i in range(10):
if i != 9:
print(i, end=", ")
else:
print(i)
Result:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
for x in range(5):
print(x, end=",")
print("\b");

python with for loop [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 10 years ago.
Hey I've got a problem with the for loop,
so let say I want to achieve printing "#" signs 5 times with for loop with out space and in one line.
for i in range(5):
print "#",
can how I get ride of the space in between so it looks like ##### instead of # # # # #???
I assume you plan on doing things in this loop other than just printing '#', if that is the case you have a few options options:
import sys
for i in range(5):
sys.stdout.write('#')
Or if you are determined to use print:
for i in range(5):
print "\b#",
or:
from __future__ import print_function
for i in range(5):
print('#', end='')
If you actually just want to print '#' n times then you can do:
n = 5
print '#'*n
or:
n = 5
print ''.join('#' for _ in range(n))
I would use a join... something like this should work:
print(''.join('x' for x in range(5)))
You can do it without a loop!
print '#' * 5
If you're making something more complicated, you can use str.join with a comprehension:
print ''.join(str(i**2) for i in range(4)) # prints 0149
print ','.join(str(i+1) for i in range(5)) # prints 1,2,3,4,5
Use the print function instead. (Note that in Python 2 print is normally a statement, but by importing print_function, it turns into a function).
from __future__ import print_function
for i in range(5):
print('#', end='')
The function supports an end keyword argument, which you can specify.
In addition to the other answers posted, you could also:
mystring = ''
for i in range(5):
mystring += '#' # Note that you could also use mystring.join() method
# .join() is actually more efficient.
print mystring
or you could even just:
print '#'*5

Categories

Resources