Consider this Python code for printing a list of comma separated values
for element in list:
print element + ",",
What is the preferred method for printing such that a comma does not appear if element is the final element in the list.
ex
a = [1, 2, 3]
for element in a
print str(element) +",",
output
1,2,3,
desired
1,2,3
>>> ','.join(map(str,a))
'1,2,3'
A ','.join as suggested in other answers is the typical Python solution; the normal approach, which peculiarly I don't see in any of the answers so far, is
print ','.join(str(x) for x in a)
known as a generator expression or genexp.
If you prefer a loop (or need one for other purposes, if you're doing more than just printing on each item, for example), there are of course also excellent alternatives:
for i, x in enumerate(a):
if i: print ',' + str(x),
else: print str(x),
this is a first-time switch (works for any iterable a, whether a list or otherwise) so it places the comma before each item but the first. A last-time switch is slightly less elegant and it work only for iterables which have a len() (not for completely general ones):
for i, x in enumerate(a):
if i == len(a) - 1: print str(x)
else: print str(x) + ',',
this example also takes advantage of the last-time switch to terminate the line when it's printing the very last item.
The enumerate built-in function is very often useful, and well worth keeping in mind!
It's very easy:
print(*a, sep=',')
Print lists in Python (4 Different Ways)
There are two options ,
You can directly print the answer using
print(*a, sep=',')
this will use separator as "," you will get the answer as ,
1,2,3
and another option is ,
print(','.join(str(x) for x in list(a)))
this will iterate the list and print the (a) and print the output as
1,2,3
That's what join is for.
','.join([str(elem) for elem in a])
print ','.join(a)
def stringTokenizer(sentense,delimiters):
list=[]
word=""
isInWord=False
for ch in sentense:
if ch in delimiters:
if isInWord: # start ow word
print(word)
list.append(word)
isInWord=False
else:
if not isInWord: # end of word
word=""
isInWord=True
word=word+ch
if isInWord: # end of word at end of sentence
print(word)
list.append(word)
isInWord=False
return list
print (stringTokenizer(u"привет парни! я вам стихами, может быть, еще отвечу",", !"))
>>> a=[1,2,3]
>>> a=[str(i) for i in a ]
>>> s=a[0]
>>> for i in a[1:-1]: s="%s,%s"%(s,i)
...
>>> s=s+","+a[-1]
>>> s
'1,2,3'
Related
I have a piece of code that does everything I need it to do and now I am making it look better and refining it. When I print the outcome, I find that the list in the statement is in square brackets and I cannot seem to remove them.
You can use map() to convert the numbers to strings, and use " ".join() or ", ".join() to place them in the same string:
mylist = [4, 5]
print(" ".join(map(str, mylist)))
#4 5
print(", ".join(map(str, mylist)))
#4, 5
You could also just take advantage of the print() function:
mylist = [4, 5]
print(*mylist)
#4 5
print(*mylist, sep=", ")
#4, 5
Note: In Python2, that won't work because print is a statement, not a function. You could put from __future__ import print_function at the beginning of the file, or you could use import __builtin__; getattr(__builtin__, 'print')(*mylist)
You could convert it to a string instead of printing the list directly:
print(", ".join(LIST))
If the elements in the list are not strings, you can convert them to string using either repr() or str() :
LIST = [1, "printing", 3.5, { "without": "brackets" }]
print( ", ".join( repr(e) for e in LIST ) )
Which gives the output:
1, 'printing', 3.5, {'without': 'brackets'}
If print is a function (which it is by default in Python 3), you could unpack the list with *:
>>> L = [3, 5]
>>> from __future__ import print_function
>>> print(*L)
3 5
You could do smth like this:
separator = ','
print separator.join(str(element) for element in myList)
Why don't you display the elements in the list one by one using the for loop instead of displaying an entire list at once like so:
# l - list
for i in range(0, len(l)):
print l[i],
These commands:
l = ["1\n2"]
print(l)
print
['1\n2']
I want to print
['1
2']
Is it possible when we generate the list outside of the print() command?
A first attempt:
l = ["1\n2"]
print(repr(l).replace('\\n', '\n'))
The solution above doesn't work in tricky cases, for example if the string is "1\\n2" it replaces, but it shouldn't. Here is how to fix it:
import re
l = ["1\n2"]
print(re.sub(r'\\n|(\\.)', lambda match: match.group(1) or '\n', repr(l)))
Only if you are printing the element itself (or each element) and not the whole list:
>>> a = ['1\n2']
>>> a
['1\n2']
>>> print a
['1\n2']
>>> print a[0]
1
2
When you try to just print the whole list, it prints the string representation of the list. Newlines belong to individual elements so get printed as newlines only when print that element. Otherwise, you will see them as \n.
You should probably use this, if you have more than one element
>>> test = ['1\n2', '3', '4\n5']
>>> print '[{0}]'.format(','.join(test))
[1
2,3,4
5]
Try this:
s = ["1\n2"]
print("['{}']".format(s[0]))
=> ['1
2']
How would I put ! after every character in a list
listOne = ["hello","world"]
How do I turn that into:
["h!e!l!l!o","w!o!r!l!d"]
Attempt:
def turn(List):
return [i for i in (list(lambda x: "%s!" % x,listOne))]
turn(listOne)
Returns:
['hello!',"world!"]
Is their another way to do this besides:
def turn(List):
x = ""
for word in words:
for letter in word:
x += "%s!" % letter
return x
turn(listOne)
I'm not a big fan of doing things like that however I do realize that may be more pythonic than what I'm trying to do which is make it as few lines as possible so. Is this possible?
You can easily achieve this with the str.join() method, and list comprehension:
>>> listOne = ['!'.join(i) for i in listOne]
>>> listOne
Output
['h!e!l!l!o', 'w!o!r!l!d']
Alternatively, as abarnert suggested, you can use the bulit-in map function.
>>> listOne = list(map('!'.join, listOne))
>>> listOne
['h!e!l!l!o', 'w!o!r!l!d']
Hope this helps!
listOne = ["hello","world"]
listTwo = ['!'.join([x for x in word]) for word in listOne]
How about this?
["!".join(s) for s in ["hello", "world"]]
Or more specific:
def turn(l):
return ["!".join(s) for s in l]
Edit: Removed wrapping of the string in list() as str.join takes every iterable
object (those that implement __iter__()), and, thus strings as well. Courtesy to #alKid.
If I have a list of strings such as:
[("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]
What should I do in order to get rid of all the 8s in each string? I tried using strip or replace in a for loop but it doesn't work like it would in a normal string (that not in a list). Does anyone have a suggestion?
Try this:
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print([s.strip('8') for s in lst]) # remove the 8 from the string borders
print([s.replace('8', '') for s in lst]) # remove all the 8s
Beside using loop and for comprehension, you could also use map
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst
A faster way is to join the list, replace 8 and split the new string:
mylist = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylist = ' '.join(mylist).replace('8','').split()
print mylist
mylist = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print mylist
j=0
for i in mylist:
mylist[j]=i.rstrip("8")
j+=1
print mylist
Here's a short one-liner using regular expressions:
print [re.compile(r"8").sub("", m) for m in mylist]
If we separate the regex operations and improve the namings:
pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]
msg = filter(lambda x : x != "8", lst)
print msg
EDIT:
For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.
Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.
To make this (kinda work?) with how the intent of the question was we could perform something similar to this
msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
I am not in an interpreter at the moment so of course mileage may vary, we may have to index so we do list(y[0]) would be the only modification to the above for this explanation purposes.
What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].
This would result in a data type that looks like this
msg = [["a", "a", "a", "a"], ["b", "b"]...]
So finally to wrap that up we would have to map it to bring them all back into the same type roughly
msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))
I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.
i have a list:
a = ['a','b','c'.........'A','B','C'.........'Z']
and i have string:
string1= 's#$%ERGdfhliisgdfjkskjdfW$JWLI3590823r'
i want to keep ONLY those characters in string1 that exist in a
what is the most effecient way to do this? perhaps instead of having a be a list, i should just make it a string? like this a='abcdefg..........ABC..Z' ??
This should be faster.
>>> import re
>>> string1 = 's#$%ERGdfhliisgdfjkskjdfW$JWLI3590823r'
>>> a = ['E', 'i', 'W']
>>> r = re.compile('[^%s]+' % ''.join(a))
>>> print r.sub('', string1)
EiiWW
This is even faster than that.
>>> all_else = ''.join( chr(i) for i in range(256) if chr(i) not in set(a) )
>>> string1.translate(None, all_else)
'EiiWW'
44 microsec vs 13 microsec on my laptop.
How about that?
(Edit: turned out, translate yields the best performance.)
''.join([s for s in string1 if s in a])
Explanation:
[s for s in string1 if s in a]
creates a list of all characters in string1, but only if they are also in the list a.
''.join([...])
turns it back into a string by joining it with nothing ('') in between the elements of the given list.
List comprehension to the rescue!
wanted = ''.join(letter for letter in string1 if letter in a)
(Note that when passing a list comprehension to a function you can omit the brackets so that the full list isn't generated prior to being evaluated. While semantically the same as a list comprehension, this is called a generator expression.)
If, you are going to do this with large strings, there is a faster solution using translate; see this answer.
#katrielalex: To spell it out:
import string
string1= 's#$%ERGdfhliisgdfjkskjdfW$JWLI3590823r'
non_letters= ''.join(chr(i) for i in range(256) if chr(i) not in string.letters)
print string1.translate(None,non_letters)
print 'Simpler, but possibly less correct'
print string1.translate(None, string.punctuation+string.digits+string.whitespace)