Python integers with trailing 'L' in a list [duplicate] - python

So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.

In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".

This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.

Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')

Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.

You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.

Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101

I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]

Related

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]

f-string syntax for unpacking a list with brace suppression

I have been examining some of my string format options using the new f-string format. I routinely need to unpack lists and other iterables of unknown length. Currently I use the following...
>>> a = [1, 'a', 3, 'b']
>>> ("unpack a list: " + " {} "*len(a)).format(*a)
'unpack a list: 1 a 3 b '
This, albeit a bit cumbersome, does the job using pre-3.6 .format notation.
The new f-string format option is interesting given runtime string concatenation. It is the replication of the number of {} that I am having problems with. In my previous example, I simply created the necessary structure and unpacked within the .format() section.
Attempts to do this yielded one variant that worked, however:
1) Both curly brackets together doesn't unpack...
>>> 'unpack a list' f' {{*a}}'
'unpack a list {*a}'
2) Adding spaces around the interior {} pair:
This works but leaves opening and closing braces {, } present:
>>> 'unpack a list' f' { {*a} }'
"unpack a list {1, 3, 'a', 'b'}"
2b) Concatenating the variants into one f-string
This made the look and syntax better, since the evaluation, apparently, is from left to right. This, however, still left the enclosing curly brackets present:
>>> f'unpack a list { {*a} }'
"unpack a list {1, 3, 'a', 'b'}"
3) Tried automatic unpacking with just {a}
Perhaps, I was overthinking the whole procedure and hoping for some form of automatic unpacking. This simply yielded the list representation with the curly brackets being replaced with [] :
>>> f'unpack a list {a}'
"unpack a list [1, 'a', 3, 'b']"
What is required to suppress the curly brackets in variant (2) above, or must I keep using the existing .format() method? I want to keep it simple and use the new capabilities offered by the f-string and not revert back beyond the python versions which pre-date what I am currently comfortable with. I am beginning to suspect that f'strings' do not offer a complete coverage of what is offered by its .format() sibling. I will leave it at that for now, since I haven't even ventured into the escape encoding and the inability to use \ in an f-string. I have read the PEP and search widely, however, I feel I am missing the obvious or what I wish for is currently not possible.
EDIT several hours later:
4) Use subscripting to manually slice off the brackets: str(a)[1:-2]
I did find this variant which will serve for some cases that I need
f'unpack a list: {str(a)[1:-2]}'
"unpack a list: 1, 'a', 3, 'b"
But the slicing is little more than a convenience and still leaves the string quotes around the resultant.
5) and the final solution from #SenhorLucas
a = np.arange(10)
print(f"{*a,}")
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Unpacking with trailing comma.
Just add a comma after the unpacked list.
a = [1, 2, 3]
print(f"Unpacked list: {*a,}")
# Unpacked list: (1, 2, 3)
There is a longer explanation to this syntax in this thread.
Since any valid Python expression is allowed inside the braces in an f-string, you can simply use str.join() to produce the result you want:
>>> a = [1, 'a', 3, 'b']
>>> f'unpack a list: {" ".join(str(x) for x in a)}'
'unpack a list: 1 a 3 b'
You could of course also write a helper function, if your real-world use case makes the above more verbose than you'd like:
def unpack(s):
return " ".join(map(str, s)) # map(), just for kicks
>>> f'unpack a list: {unpack(a)}'
'unpack a list: 1 a 3 b'
Simple Python is probably more clear:
>>> 'unpack a list: ' + ' '.join(str(x) for x in a)
'unpack a list: 1 a 3 b'
With slicing:
>>> 'unpack a list: ' + ' '.join([str(x) for x in a][1:3])
'unpack a list: a 3'
I don't think that this is the way f-Strings are meant to be used. At best I can imagine preparing a print() compatible tuple, like:
mixed = [1, "list_string", 2]
number = 23
answer = 46
info = 'Content:', *mixed, f'{number} {answer}'
print(*info) # default sep=' '
Output
Content: 1 list_string 2 23 46
I made this a while back, to include commas Oxford style.
def unpack_list(lst): # Oxford comma
if not isinstance(lst, str):
lst = [str(item) for item in lst]
if len(lst) == 0:
return
if len(lst) == 1:
return ", ".join(lst)
if len(lst) == 2:
return ", and ".join(lst)
else:
first_part = lst[:-1]
last_part = lst[-1]
return ", ".join(first_part) + ", and " + last_part

How to print items within lists in a list

Hear me out, I do not simply want someone to solve this problem for me. I know it is not 100% complete yet, but currently when I run the program I get an error about "Can't convert 'list' object to str implicitly" I'm looking for help on how to fix this and why it is does this.
Here is the problem
Write code to print out each thing in the list of lists, L, with a '*' after it like
1*2*3*4*...8*a*b*c*d*
This requires knowing the print statement and using the end or sep argument option
Here is my list, sorry for not putting it in earlier
L = [[1,2,3,4],[5,6,7,8],['a','b','c','d']]
Here is my code at the moment
def ball(x): #random function name with one parameter
q = '' #
i = 0
if type(x) != list: #verifies input is a list
return"Error"
for i in x: #Looks at each variable in list
for j in i: #Goes into second layer of lists
q = q + j + '*'
print(q)
The reason for your error
"Can't convert 'list' object to str implicitly"
is that you're using the wrong variable in your nested for loops. Where you're concatenating values to your q variable, you mistakenly put q = q + i when you wanted q = q + j. You also will want to cast the value of j as a string so it can be concatenated with q. In order to get your desired output, you can simply add an asterisk into that statement - something like the following: q = q + str(j) + '*'. On a completely unrelated note, your else statement that just has "Mistake" in it should be removed completely - it doesn't follow an if and it doesn't actually return or assign to a variable.
Note that this is not the most elegant way to go about solving this problem. I agree with ilent2 that you should take a look at both list comprehension and the str.join() method.
If you have a list of strings,
myList = ['a', '123', 'another', 'and another']
You can join them using the str.join function:
Help on method_descriptor:
join(...)
S.join(iterable) -> string
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
myString = '#'.join(myList)
If your list contains mixed types or non-strings you need to convert each item to a string first:
anotherList = [1, 2, 'asdf', 'bwsg']
anotherString = '*'.join([str(s) for s in anotherList])
You might want to read about list comprehension or more about the join function. Note, the above doesn't print the output (unless you are using the interactive console), if you want the output to be printed you will need call print too
print myString
print anotherString
And, if you are working with lists-of-lists you may need to change how you convert each sub-list into a string (depending on your desired output):
myListList = [[1, 2, 3, 4], [2, 3, 6, 5], [6, 4, 3, 1]]
myOtherString = '#'.join(['*'.join([str(s) for s in a]) for a in myListList])
The last line is a little complicated to read, you might want to rewrite it as a nested for loop instead.

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']

How to "properly" print a list?

So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')
Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.
You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.
Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101
I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]

Categories