Changing up the contents of a list - python

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)

Related

How to remove free space from list of integer , I want final result in list rather than string [duplicate]

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]) + "]")

Get every 2nd and 3rd characters of a string in Python

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'

How to add a word before the last word in list?

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]

Append a portion of a string to a list

I was wondering how one can append a portion of a string to a list? Is there an option of both appending based on the position of characters in the string, and another option that is able to take a specific character of interest? For instance, If I had the string "2 aikjhakihaiyhgikjewh", could I not only append the part of the string that was in positions 3-4 but also append the "2" as well? I'm a beginner, so I'm still kinda new to this python thing. Thanks.
You can use slicing to reference a portion of a string like this:
>>> s = 'hello world'
>>> s[2:5]
'llo'
You can append to a list using the append method:
>>> l = [1,2,3,4]
>>> l.append('Potato')
>>> l
[1, 2, 3, 4, 'Potato']
Best way to learn this things in python is to open an interactive shell and start typing commands on it. I suggest ipython as it provides autocomplete which is great for exploring objects methods and properties.
You can append a portion of a string to a list by using the .append function.
List = []
List.append("text")
To append several parts of the string you can do the following:
List = []
String = "2 asdasdasd"
List.append(String[0:2] + String[3:5])
This would add both sections of the string that you wanted.
Use slicing to accomplish what you are looking for:
mystr = "2 aikjhakihaiyhgikjewh"
lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
print lst
This runs as:
>>> mystr = "2 aikjhakihaiyhgikjewh"
>>> lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
>>> print lst
['2', 'i', 'k']
>>>
Slicing works by taking certain parts of an object:
>>> mystr
'2 aikjhakihaiyhgikjewh'
>>> mystr[0]
'2'
>>> mystr[-1]
'h'
>>> mystr[::-1]
'hwejkighyiahikahjkia 2'
>>> mystr[:-5]
'2 aikjhakihaiyhgi'
>>>
You are describing 2 separate operations: slicing a string, and extending a list. Here is how you can put the two together:
In [26]: text = "2 aikjhakihaiyhgikjewh"
In [27]: text[0], text[3:5]
Out[27]: ('2', 'ik')
In [28]: result = []
In [29]: result.extend((text[0], text[3:5]))
In [30]: result
Out[30]: ['2', 'ik']

Python: Convert a list into a normal value

I have a list
a = [3]
print a
[3]
I want ot convert it into a normal integer
print a
3
How do I do that?
a = a[0]
print a
3
Or are you looking for sum?
>>> a=[1]
>>> sum(a)
1
>>> a=[1,2,3]
>>> sum(a)
6
The problem is not clear. If a has only one element, you can get it by:
a = a[0]
If it has more than one, then you need to specify how to get a number from more than one.
I imagine there are many ways.
If you want an int() you should cast it on each item in the list:
>>> a = [3,2,'1']
>>> while a: print int(a.pop())
1
2
3
That would also empty a and pop() off each back handle cases where they are strings.
You could also keep a untouched and just iterate over the items:
>>> a = [3,2,'1']
>>> for item in a: print int(item)
3
2
1
To unpack a list you can use '*':
>>> a = [1, 4, 'f']
>>> print(*a)
1 4 f

Categories