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]))
Related
I got a working solution to this question with my second attempt. But I'm wondering why the first option doesn't work as well.
The question is:
Complete the function to replace the word test with cat and print the new string
my code (working solution):
def replaceTest(mystring):
answer = mystring.replace("test", "cat")
print(answer)
replaceTest('This is a test')
# output:
# This is a cat
my code (solution that doesn't work):
def replaceTest(mystring):
stringSplit = mystring.split()
for i in stringSplit:
if i == 'test':
i = 'cat'
answer = " ".join(stringSplit)
print(answer)
print(replaceTest('This is a test'))
# output:
# This is a test
# None
I can't see why it doesn't work. I think I'm iterating over each item in the list and saying if that item is test, make it cat instead. And then making the list into a string. Where did i go wrong?
With i = 'cat' you are just assigning to the loop variable, which is then discarded. You need to assign to the original strinSplit list (stringSplit[i] = 'cat') where by i is the index of stringSplit, obtained from enumerate:
def replaceTest(mystring):
stringSplit = mystring.split()
for i, word in enumerate(stringSplit):
if word == 'test':
stringSplit[i] = 'cat'
answer = " ".join(stringSplit)
print(answer)
replaceTest('This is a test')
Some improvements while still using your original logic: Having an index in a loop used to access list elements is awkward and error-prone. In this case (and many others) you can avoid it using a list comprehension instead. Also, I assume you wouldn't really want to print inside the function but instead return the modified string so you can use it further:
def replaceTest(mystring):
string_split_replace = ["cat" if word == "test" else word
for word in mystring.split()]
return " ".join(string_split_replace)
print(replaceTest('This is a test'))
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]))
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 6 years ago.
I have code like this:
def reverse(text):
l=len(text)
while ((l-1)!=0):
print (str(text[l-1]))
l=l-1
print (str(text[0]))
a=reverse("abc!de#fg")
The output is:
g
f
#
e
d
!
c
b
a
but I want to combine these individual characters and want out put like this:
gf#ed!cba
To print without the newline at the end of each line do:
print('text', end='')
To take a list of characters and make them one string, do:
''.join(list_of_characters)
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
print (reverse('abc!de#fg'))
The simplest way to reverse a string:
In [1]: a = "abc!de#fg"
In [2]: print(a[::-1])
gf#ed!cba
The python print statement adds a newline by default. An easy way to print without newlines is
sys.stdout.write('some text')
# or
print('some text', end='')
You will need to concatenate them and then print the string result.
This is because the function print automatically does a break line.
A fix would be:
def reverse(text):
l = len(text)
aux = ''
while l-1 != 0:
aux += str(text[l-1])
l = l - 1
print (aux)
a = reverse("abc!de#fg")`
P.S: Try to avoid redundant parenthesis =)
Hey try to put the print value in variable and print that at the end. Like this.
def reverse(text):
l=len(text)
output = ""
while ((l-1)!=0):
output += (str(text[l-1]))
l=l-1
output +=(str(text[0]))
print output
a=reverse("abc!de#fg")
Hope this helps
In Python, the simplest way to reverse a Sequence is with a slice:
>>> string="abc!de#fg"
>>> print(string[::-1])
gf#ed!cba
Slicing will give you a copy of the sequence in reverse order.
In general, you want a function to do one thing. Returning a value and printing some output are separate concerns, so they should not be conflated in the same function. If you have a function that returns a reversed string, you can simply print the function:
print(reverse("abc"))
Then, you can see that your actual algorithm is fine, if not entirely Pythonic:
def reverse(text):
l=len(text)
output = ""
while ((l-1)!=0):
output += (str(text[l-1]))
l=l-1
output +=(str(text[0]))
return output
You can clearly see now that it's the print function in your way.
I am doing a program that changes a number in base 10 to base 7, so i did this :
num = int(raw_input(""))
mod = int(0)
list = []
while num> 0:
mod = num%7
num = num/7
list.append(mod)
list.reverse()
for i in range (0,len(list)):
print list[i],
But if the number is 210 it prints 4 2 0 how do i get rid of the spaces
You can use join with list comprehension:
>>> l=range(5)
>>> print l
[0, 1, 2, 3, 4]
>>> ''.join(str(i) for i in l)
'01234'
Also, don't use list as a variable name since it is a built-in function.
In python 3 you can do like this :
print(*range(1,int(input())+1), sep='')
Your output will be like this if input = 4 :
1234
Convert the list to a string, and replace the white spaces.
strings = ['hello', 'world']
print strings
>>>['hello', 'world']
print str(strings).replace(" ", "")
>>>['hello','world']
Take a look at sys.stdout. It's a file object, wrapping standard output. As every file it has write method, which takes string, and puts it directly to STDOUT. It also doesn't alter nor add any characters on it's own, so it's handy when you need to fully control your output.
>>> import sys
>>> for n in range(8):
... sys.stdout.write(str(n))
01234567>>>
Note two things
you have to pass string to the function.
you don't get newline after printing.
Also, it's handy to know that the construct you used:
for i in range (0,len(list)):
print list[i],
is equivalent to (frankly a bit more efficient):
for i in list:
print i,
Doing the following worked for me in Python3
print(*list,sep='')
You can use below code snippet for python3
print(*list(range(1, n + 1)), sep='')
* will remove initial and end character like [{}]
sep = '' will remove the spaces between item.
Use list_comprehension.
num= int(raw_input(""))
mod=int(0)
list =[]
while num> 0:
mod=num%7
num=num/7
list.append(mod)
list.reverse()
print ''.join([str(list[i]) for i in range (0,len(list))])
The print() function has an argument to specify the end character which by default is '\n'. Specifying the end character as '' and printing using a loop will do what you are looking for:
n_list = [1,2,3,4,5]
for i in n_list:
print(i, end='')
s = "jay"
list = [ i for i in s ]
It you print list you will get:
['j','a','y']
new_s = "".join(list)
If you print new_s:
"jay"
Here's a code for selection sort but it doesn't print the sorted list. How can I show it?
badlist = input("Enter list: ")
def select(badlist):
l = list[:]
sorted = []
while len(l):
lowest == l[0]
for x in l:
if x < lowest:
lowest = x
sorted.append(lowest)
l.remove(lowest)
return sorted
select(badlist)
if you type select(badlist) in Python shell is should show the result however if you're running your script as file you need to use print statement, as print select(badlist).
Expanding on my comment:
Why not simply use the builtin sorted(list) and then you can just have your whole code be:
print sorted(input("Enter list: "))
Use print.
If you are using Python 2.x print is a keyword:
result = select(badlist)
print result
In Python 3.x print is a function and you must use parentheses:
result = select(badlist)
print(result)
You also have at least two other errors:
Your function parameter is called badlist but you never use it.
The == operator is equality comparison. You need = for assignment.
Also your algorithm will be very slow, requiring O(n2) operations.