python with for loop [duplicate] - python

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

Related

How do you convert the quotient of a division of two polynomials to a standard polynomial instead of a tuple in Python [duplicate]

I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))

Python 2 equivelant of print(*array) [duplicate]

I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))

using print with a comma in python 3 [duplicate]

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

In Python, how can I print out a board of numbers representing tic-tac-toe, with a "|" in between each number?

I want to be able to rewrite the code in as few lines as possible, possibly in list comprehension syntax. Here is what the output should be:
1|2|3
4|5|6
7|8|9
This is what I have thought up. The separator doesn't actually print the "|". Any suggestions?
for i in [1,2,3,4,5,6,7,8,9]:
print(i, sep = "|", end = "")
if (i) % 3 == 0:
print()
>>> numbers = range(1, 10)
>>> print(('{}|{}|{}\n' * 3).format(*numbers))
1|2|3
4|5|6
7|8|9
Just print it.
>>> print('1|2|3\n4|5|6\n7|8|9')
1|2|3
4|5|6
7|8|9
To clarify: Yes, I'm obviously assuming that really exactly these numbers shall be printed. I think it's a reasonable assumption, given that the OP also only showed those numbers both in the desired output and in the code, didn't say anything about more flexibility (really should have if it were required), and tic-tac-toe has X and O, not numbers. I suspect this is for showing the user which number to enter for which field during play.
I like format the most because it offers the best flexibility:
moves = [' ', ' ',' ',' ', 'x',' ',' ', ' ','o']
board = "|{}|{}|{}|\n|{}|{}|{}|\n|{}|{}|{}|\n"
print(board.format(*moves)
Modify the items in that list and run that same print statement for an on-the-go solution.
And there, I managed to slim it down to 3 lines. If I wasn't initializing the list, it would only be 2 lines.
the easiest and most elegant way to do it in python 3 using print:
for i in 1,4,7:
print(i,i+1,i+2, sep='|')
Or using range:
for i in range(1,10,3):
print(*range(i,i+3), sep='|')
Also there is a good reading here about iterable unpacking operator: Additional Unpacking
Also here is one-liner, not the shortest one but very readable:
print('\n'.join(('{}|{}|{}'.format(i,i+1,i+2) for i in (1,4,7))))
And original one-liner from #Stefan Pochmann's comment:
print(('{}|{}|{}\n' * 3).format(*range(1, 10)), end='')
Output for all is the same:
1|2|3
4|5|6
7|8|9
print('\n'.join(['|'.join([str(c) for c in s[i:i+3]]) for i in range(0,9,3)]))
Don't use this (but it works). This assumes your array is in a variable named s
If you want something that is purely the smallest amount of lines, you can use the ternary syntax:
for i in range(1,10):
print(i,end='|\n') if (i) % 3 == 0 else print(i,end = "|")
Output:
1|2|3
4|5|6
7|8|9
sep doesn't work when you only give a single thing to print
>>>print(1, sep='|')
1
>>> print(1,2,3, sep='|')
1|2|3
Could do this instead
for i in range(1,10):
if i % 3 == 0:
print(i, end="\n")
else:
print(i, end="|")
Shortening to a ternary
for i in range(1,10):
print(i, end="\n") if i % 3 == 0 else print(i, end="|")
Output
1|2|3
4|5|6
7|8|9
If we're going to code golf, lets code golf properly...
One line:
print("".join(str(i)+'\n|'[i%3>0]for i in range(1,10)))
You can make it one character shorter when you realise that the indexer >0 is actually longer than repeating the pipe (|):
print("".join(str(i)+'\n||'[i%3]for i in range(1,10)))
This gives:
1|2|3
4|5|6
7|8|9
If you need even shorter, a for loop technically doesn't need to be on a new line, also in Python 3 print will print every *args, until the *kwargs.
for i in range(1,10,3):print(i,i+1,i+2,sep='|')
pass # Pass not needed, just shows syntactically how it works.
The first line above is probably the shortest you can get, without just printing the string as is.

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.

Categories

Resources