Related
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]))
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 remove items from a list while iterating?
(25 answers)
Correct code to remove the vowels from a string in Python
(13 answers)
Closed 6 years ago.
I just started to learn Python in codacademy. I was trying to do anti-vowel function, but found the following problem with 'u'.
def anti_vowel(text):
a = []
for i in text:
a.append(i)
for item in a:
if item in "aeiouAEIOU":
a.remove(item)
print ''.join(a)
print anti_vowel("Hey You!")
print anti_vowel("Hey look Words!")
print anti_vowel("aeiouAEIOU")
It printed
"Hy Yu!"
"Hy lk Words!"
"eoAIU"
Instead of
"Hy Y!"
"Hy lk Wrds!"
""
Somehow, some vowels was not removed es expected.
I found many alternatives for the function.
However, please help me identify the mistake of the current code.
There's no need to use remove, and there's no need to iterate twice. Rather, as you iterate, check whether the item is a vowel and only append if it is not.
def anti_vowel(text):
a = []
for i in text:
if i not in "aeiouAEIOU":
a.append(i)
print ''.join(a)
When you look very closely at the remaining vowels, you can see that all those vowels remain that immediately follow one another. In your last example, a (removed) e (stays) i (removed) o (stays) and so on.
This is because you are iterating over a list and at the same time you are modifying it.
To solve the problem, you should make a copy of the list. Then you can iterate over the original one while modifying the copy.
Removing items while iterating is not a good idea.
Do it in one line with a generator comprehension passed to str.join
def anti_vowel(text):
return ''.join(item for item in text if item not in "aeiouAEIOU")
or maybe more performant using a set for faster letter lookup (not sure converting to lowercase would speed this up since it creates a new string for that)
s=set("aeiouAEIOU")
def anti_vowel(text):
return ''.join(item for item in text if item not in s)
Like others have already stated, you are modifying your list while iterating through it. I did want to suggest a python built-in option for this task, though for 3.x > Python > 2.6:
print "Hey You!".translate(None, "aeiouAEIOU")
In Python 3.x you'll need to take account for the standard Unicode string and translate it first:
translation = dict.fromkeys(map(ord, "aeiouAEIOU"), None)
print("Hey You!".translate(translation))
def anti_vowel(text):
a = []
for i in text:
a.append(i)
b = a[:]
for item in a:
if item in "aeiouAEIOU":
b.remove(item)
print (''.join(b))
print (anti_vowel("Hey You!"))
print (anti_vowel("Hey look Words!"))
print (anti_vowel("aeiouAEIOU"))
Why not try recursively like this?
def anti_vowel(s):
if not s:
return s
elif s[0] in "aeiouAEIOU":
return anti_vowel(s[1:])
return s[0] + anti_vowel(s[1:])
print (anti_vowel("Hey You!"))
print (anti_vowel("Hey look Words!"))
print (anti_vowel("aeiouAEIOU"))
Output:
Hy Y!
Hy lk Wrds!
you are removing item from list while traversing so thats creating a problem.
Moreover there is no need to traverse the so many times.
you could use:
def anti_vowel(text):
a = []
for i in text:
if i not in "aeiouAEIOU":
a.append(i)
print ''.join(a)
or I would say instead of using list use string like this :
def anti_vowel(text):
a = ""
for item in text:
if item not in "aeiouAEIOU":
a+=item
print a
Edited:
using ''.join(list) is faster than using string cancatenation as pointed out by #jean in the comment section.
You could also join the result of a list comprehension, like:
def anti_vowel(text):
return "".join([char for char in text if char not in "aeiouAEIOU"])
Be sure to let your functions return their results if you want the function to do more than just printing to the terminal (for example if you want to use the returned value somehow). There's no need to print the results of a function that prints its result and returns None (which is the case if there are no return statements inside).
The [char for char in text ...] part of the list comprehension is simply a for loop over the characters in the string named text. The [... if char not in "aeiouAEIOU"] excludes the characters who are present in the "aeiouAEIOU" string. Finally, "".join([ ... ]) merges the non-excluded characters together to form a string which by the return statement is returned.
I am trying to reverse words of a string, but having difficulty, any assistance will be appreciated:
S = " what is my name"
def reversStr(S):
for x in range(len(S)):
return S[::-1]
break
What I get now is: eman ym si tahw
However, I am trying to get: tahw is ym eman (individual words reversed)
def reverseStr(s):
return ' '.join([x[::-1] for x in s.split(' ')])
orig = "what is my name"
reverse = ""
for word in orig.split():
reverse = "{} {}".format(reverse, word[::-1])
print(reverse)
Since everyone else's covered the case where the punctuation moves, I'll cover the one where you don't want the punctuation to move.
import re
def reverse_words(sentence):
return re.sub(r'[a-zA-Z]+', lambda x : x.group()[::-1], sentence)
Breaking this down.
re is python's regex module, and re.sub is the function in that module that handles substitutions. It has three required parameters.
The first is the regex you're matching by. In this case, I'm using r'\w+'. The r denotes a raw string, [a-zA-Z] matches all letters, and + means "at least one".
The second is either a string to substitute in, or a function that takes in a re.MatchObject and outputs a string. I'm using a lambda (or nameless) function that simply outputs the matched string, reversed.
The third is the string you want to do a find in a replace in.
So "What is my name?" -> "tahW si ym eman?"
Addendum:
I considered a regex of r'\w+' initially, because better unicode support (if the right flags are given), but \w also includes numbers and underscores. Matching - might also be desired behavior: the regexes would be r'[a-zA-Z-]+' (note trailing hyphen) and r'[\w-]+' but then you'd probably want to not match double-dashes (ie --) so more regex modifications might be needed.
The built-in reversed outputs a reversed object, which you have to cast back to string, so I generally prefer the [::-1] option.
inplace refers to modifying the object without creating a copy. Yes, like many of us has already pointed out that python strings are immutable. So technically we cannot reverse a python string datatype object inplace. However, if you use a mutable datatype, say bytearray for storing the string characters, you can actually reverse it inplace
#slicing creates copy; implies not-inplace reversing
def rev(x):
return x[-1::-1]
# inplace reversing, if input is bytearray datatype
def rev_inplace(x: bytearray):
i = 0; j = len(x)-1
while i<j:
t = x[i]
x[i] = x[j]
x[j] = t
i += 1; j -= 1
return x
Input:
x = bytearray(b'some string to reverse')
rev_inplace(x)
Output:
bytearray(b'esrever ot gnirts emose')
Try splitting each word in the string into a list (see: https://docs.python.org/2/library/stdtypes.html#str.split).
Example:
>>string = "This will be split up"
>>string_list = string.split(" ")
>>string_list
>>['This', 'will', 'be', 'split', 'up']
Then iterate through the list and reverse each constituent list item (i.e. word) which you have working already.
def reverse_in_place(phrase):
res = []
phrase = phrase.split(" ")
for word in phrase:
word = word[::-1]
res.append(word)
res = " ".join(res)
return res
[thread has been closed, but IMO, not well answered]
the python string.lib doesn't include an in place str.reverse() method.
So use the built in reversed() function call to accomplish the same thing.
>>> S = " what is my name"
>>> ("").join(reversed(S))
'eman ym si tahw'
There is no obvious way of reversing a string "truly" in-place with Python. However, you can do something like:
def reverse_string_inplace(string):
w = len(string)-1
p = w
while True:
q = string[p]
string = ' ' + string + q
w -= 1
if w < 0:
break
return string[(p+1)*2:]
Hope this makes sense.
In Python, strings are immutable. This means you cannot change the string once you have created it. So in-place reverse is not possible.
There are many ways to reverse the string in python, but memory allocation is required for that reversed string.
print(' '.join(word[::-1] for word in string))
s1 = input("Enter a string with multiple words:")
print(f'Original:{s1}')
print(f'Reverse is:{s1[::-1]}')
each_word_new_list = []
s1_split = s1.split()
for i in range(0,len(s1_split)):
each_word_new_list.append(s1_split[i][::-1])
print(f'New Reverse as List:{each_word_new_list}')
each_word_new_string=' '.join(each_word_new_list)
print(f'New Reverse as String:{each_word_new_string}')
If the sentence contains multiple spaces then usage of split() function will cause trouble because you won't know then how many spaces you need to rejoin after you reverse each word in the sentence. Below snippet might help:
# Sentence having multiple spaces
given_str = "I know this country runs by mafia "
tmp = ""
tmp_list = []
for i in given_str:
if i != ' ':
tmp = tmp + i
else:
if tmp == "":
tmp_list.append(i)
else:
tmp_list.append(tmp)
tmp_list.append(i)
tmp = ""
print(tmp_list)
rev_list = []
for x in tmp_list:
rev = x[::-1]
rev_list.append(rev)
print(rev_list)
print(''.join(rev_list))
output:
def rev(a):
if a == "":
return ""
else:
z = rev(a[1:]) + a[0]
return z
Reverse string --> gnirts esreveR
def rev(k):
y = rev(k).split()
for i in range(len(y)-1,-1,-1):
print y[i],
-->esreveR gnirts
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"