I have this code here. I want to print a list without spaces. Here l is a list with 3 elements that I am trying to print:
>>> l=[]
>>> l.append(5)
>>> l.append(6)
>>> l.append(7)
>>> print(l)
I get in the output:
[5, 6, 7]
but I want to get:
[5,6,7]
What should I add to the syntax in append or in print to print the list without spaces?
You need to use something like:
print('[{0}]'.format(','.join(map(str, l))))
You can modify the result if it isn't too big:
print(repr(l).replace(' ', ''))
You could convert it to a string and then replace the spaces. E.g:
print ("{}".format(l)).replace(' ', '')
Join the list elements.
print("[" + ",".join([str(i) for i in l]) + "]")
I know that my_str[1::3] gets me every 2nd character in chunks of 3, but what if I want to get every 2nd and 3rd character? Is there a neat way to do that with slicing, or do I need some other method like a list comprehension plus a join:
new_str = ''.join([s[i * 3 + 1: i * 3 + 3] for i in range(len(s) // 3)])
I think using a list comprehension with enumerate would be the cleanest.
>>> "".join(c if i % 3 in (1,2) else "" for (i, c) in enumerate("peasoup booze scaffold john"))
'eaou boz safol jhn'
Instead of getting only 2nd and 3rd characters, why not filter out the 1st items?
Something like this:
>>> str = '123456789'
>>> tmp = list(str)
>>> del tmp[::3]
>>> new_str = ''.join(tmp)
>>> new_str
'235689'
Hello I'm new to this programming language
I wanted to add the word 'and' before the last item in my list.
For example:
myList = [1,2,3,4]
If I print it the output must be like:
1,2,3 and 4
Here is one way, but I have to convert the int's to strings to use join:
myList = [1,2,3,4]
smyList = [str(n) for n in myList[:-1]]
print(",".join(smyList), 'and', myList[-1])
gives:
1,2,3 and 4
The -1 index to the list gives the last (rightmost) element.
This may not be the most elegant solution, but this is how I would tackle it.
define a formatter function as follows:
def format_list(mylist)
str = ''
for i in range(len(mylist)-1):
str.append(str(mylist[i-1]) + ', ')
str.append('and ' + str(mylist[-1]))
return str
then call it like this
>>> x = [1,2,3,4]
>>> format_list(x)
1, 2, 3, and 4
You can also use string formating:
l = [1,2,3,4]
print("{} and {}".format(",".join(str(i) for i in l[:-1]), l[-1]))
#'1,2,3 and 4'
Using join (to join list elements) and map(str,myList) to convert all integers inside list to strings
','.join(map(str,myList[:-1])) + ' and ' + str(myList[-1])
#'1,2,3 and 4'
Your question is misleading, if you are saying "How to add a word before the last word in list?" it means you want to add 'and' string before last item in the list , while many people are giving answer using .format() method , You should specify you want 'and' for printing or in list for further use of that result :
Here is list method according to your question :
myList = [1,2,3,4]
print(list((lambda x,y:(x+['and']+y))(myList[:-1],myList[-1:])))
output:
[1, 2, 3, 'and', 4]
Given a list with several names as a parameter, I was wondering if there was a way to split the names by first and last and create a 2d list of all first names and all last names. For example given:
lst=(["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"])
the output should be:
[["Leonoardo","Brad","Angelina"],["DiCaprio","Pitt","Jolie"]]
I know that I need to iterate over the given list, and append the first names and last names to a new lists but I'm not quite sure how to go about it.
This is what I've got so far:
fname=[]
lname=[]
for i in nlst:
i.split()
fname.append(i[0])
lname.append(i[1])
return lname,fname
You can use a simple list comprehension:
>>> lst=(["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"])
>>> new = [[item.split(',')[1] for item in lst], [item.split(',')[0] for item in lst]]
>>> new
[['Leonardo', ' Brad', ' Angelina'], ['DiCaprio', 'Pitt', 'Jolie']]
Or you can zip it:
>>> x = [item.split(',') for item in lst]
>>> list(reversed(zip(*x)))
[('Leonardo', ' Brad', ' Angelina'), ('DiCaprio', 'Pitt', 'Jolie')]
This might help you:
list_names = []
list_last =[]
lst=["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"]
for element in lst:
list_names.append(element.split(',')[0])
list_last.append(element.split(',')[1])
Let me know if you need anything else
a function to return the names after splitting.
def split_list(the_list=["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"]):
list_2d = [[],[]]
for full_name in the_list:
first_name, second_name = full_name.split(',')
list_2d[0].append(first_name)
list_2d[1].append(second_name)
return list_2d
print split_list()
According your code, you can try this:
lst=(["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"])
fname=[]
lname=[]
for i in lst:
fname.append(i.split(",")[0])
lname.append(i.split(",")[1])
print [lname,fname]
You can split and transpose:
lst = ["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"]
print([list(ele) for ele in zip(*(ele.split(",") for ele in lst))])
Or use map:
print(list(map(list, zip(*(ele.split(",") for ele in lst)))))
[['DiCaprio', 'Pitt', 'Jolie'], ['Leonardo', ' Brad', ' Angelina']]
If you need the order reversed:
print(list(map(list, zip(*(reversed(ele.split(",")) for ele in lst)))))
[['Leonardo', ' Brad', ' Angelina'], ['DiCaprio', 'Pitt', 'Jolie']]
For python2 you can use izip and the remove the list call on map:
from itertools import izip
print(map(list, izip(*(reversed(ele.split(",")) for ele in lst))))
You can use zip function :
>>> l=["DiCaprio,Leonardo","Pitt, Brad", "Jolie, Angelina"]
>>> zip(*[i.split(',') for i in l])[::-1]
[('Leonardo', ' Brad', ' Angelina'), ('DiCaprio', 'Pitt', 'Jolie')]
If you want the result as list you can convert to list with map function :
>>> map(list,zip(*[i.split(',') for i in l])[::-1])
[['Leonardo', ' Brad', ' Angelina'], ['DiCaprio', 'Pitt', 'Jolie']]
You could use a regex:
>>> re.findall(r'(\w+),\s*(\w+);?', ';'.join(lst))
[('DiCaprio', 'Leonardo'), ('Pitt', 'Brad'), ('Jolie', 'Angelina')]
Then use either zip or map to transpose the list of tuples:
>>> map(None, *re.findall(r'(\w+),\s*(\w+);?', ';'.join(lst)))
[('DiCaprio', 'Pitt', 'Jolie'), ('Leonardo', 'Brad', 'Angelina')]
On Python 3, you can't use map that way. Instead, you would do:
>>> list(map(lambda *x: [e for e in x], *re.findall(r'(\w+),\s*(\w+);?', ';'.join(lst))))
Then reverse the order and make a list of lists rather than list of tuples if you wish:
>>> lot=map(None, *re.findall(r'(\w+),\s*(\w+);?', ';'.join(lst)))
>>> [list(lot[1]), list(lot[0])]
[['Leonardo', 'Brad', 'Angelina'], ['DiCaprio', 'Pitt', 'Jolie']]
If i have a list of integers such as [1,2,3]
How would I remove the [ and , to make it just 1 2 3 with spaces
I tried converting it to a string and using the split method but I don't know how to convert back into a integer and print it out. I have this:
z = map(str,x.split(" ,"))
but like I said i don't know how to make that a integer again and print it out.
I tried:
t = map(int,z)
and that did not work.
>>>x = [1,2,3]
1 2 3
For convert to string with space you need to convert all the entries to str with map(str,l) and join them with ' '.join , the for reverse to list first you need to split the string with str.split() and then convert to int with map :
>>> l=[1,2,3]
>>> ' '.join(map(str,l))
'1 2 3'
>>> string=' '.join(map(string,l))
>>> map(int,string.split())
[1, 2, 3]
Your question doesn't really make sense. the [, ,, and ] are what DEFINE it as a list. Those markings are simply the way that Python shows it is a list. If you want to DISPLAY it as something other than a list, you probably want str.join. However that requires that each element in the list be a string, so you're left with either:
>>> some_list = [1,2,3]
>>> print(some_list)
[1, 2, 3]
>>> print(" ".join(map(str, some_list)))
1 2 3
or:
>>> print(" ".join([str(el) for el in some_list]))
1 2 3
' '.join(str(i) for i in my_list)