I am writing a piece of code that should output a list of items separated with a comma. The list is generated with a for loop:
for x in range(5):
print(x, end=",")
The problem is I don't know how to get rid of the last comma that is added with the last entry in the list. It outputs this:
0,1,2,3,4,
How do I remove the ending ,?
Pass sep="," as an argument to print()
You are nearly there with the print statement.
There is no need for a loop, print has a sep parameter as well as end.
>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4
A little explanation
The print builtin takes any number of items as arguments to be printed. Any non-keyword arguments will be printed, separated by sep. The default value for sep is a single space.
>>> print("hello", "world")
hello world
Changing sep has the expected result.
>>> print("hello", "world", sep=" cruel ")
hello cruel world
Each argument is stringified as with str(). Passing an iterable to the print statement will stringify the iterable as one argument.
>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']
However, if you put the asterisk in front of your iterable this decomposes it into separate arguments and allows for the intended use of sep.
>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world
>>> print(*range(5), sep="---")
0---1---2---3---4
Using join as an alternative
The alternative approach for joining an iterable into a string with a given separator is to use the join method of a separator string.
>>>print(" cruel ".join(["hello", "world"]))
hello cruel world
This is slightly clumsier because it requires non-string elements to be explicitly converted to strings.
>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4
Brute force - non-pythonic
The approach you suggest is one where a loop is used to concatenate a string adding commas along the way. Of course this produces the correct result but its much harder work.
>>>iterable = range(5)
>>>result = ""
>>>for item, i in enumerate(iterable):
>>> result = result + str(item)
>>> if i > len(iterable) - 1:
>>> result = result + ","
>>>print(result)
0,1,2,3,4
You can use str.join() and create the string you want to print and then print it. Example -
print(','.join([str(x) for x in range(5)]))
Demo -
>>> print(','.join([str(x) for x in range(5)]))
0,1,2,3,4
I am using list comprehension above, as that is faster than generator expression , when used with str.join .
To do that, you can use str.join().
In [1]: print ','.join(map(str,range(5)))
0,1,2,3,4
We will need to convert the numbers in range(5) to string first to call str.join(). We do that using map() operation. Then we join the list of strings obtained from map() with a comma ,.
Another form you can use, closer to your original code:
opt_comma="" # no comma on first print
for x in range(5):
print (opt_comma,x,sep="",end="") # we are manually handling sep and end
opt_comma="," # use comma for prints after the first one
print() # force new line
Of course, the intent of your program is probably better served by the other, more pythonic answers in this thread. Still, in some situations, this could be a useful method.
Another possibility:
for x in range(5):
if x:
print (", ",x,end="")
else:
print (x, end="")
print()
for n in range(5):
if n == (5-1):
print(n, end='')
else:
print(n, end=',')
An example code:
for i in range(10):
if i != 9:
print(i, end=", ")
else:
print(i)
Result:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
for x in range(5):
print(x, end=",")
print("\b");
Related
I wrote a code that accepts multiple numbers and converts them into a list of integers. But I get them with spaces.
For example: I enter as input: 1,2,3,4,5 (with commas).
I get a list of [1, 2, 3, 4, 5]
Now I just need to delete the spaces but It's not working, I need it to look something like this [1,2,3,4,5].
I tried doing it this way:
numbers = input().split(',')
for i in range(0, len(numbers)):
numbers[i] = int(numbers[i])
mylist = str(numbers).replace(' ','')
print(mylist)
This causes the square parentheses to be considered as items.
How do I delete the spaces the right way?
I think you are conflating the list and the representation of the list. The list itself doesn't have spaces, or even commas, it just has the items (in your case, the numbers). The representation of the list is just that - a way to represent the data inside of it in a normal, standard way. That standard includes commas and spaces.
If you want a new thing that represents the list and its items in the way you are saying, you can do that by making a new string just like that.
str(numbers).replace(' ','')
This has two functions in it, chained together. First, we do str(numbers) to get a string that is the string-representation of the list. This will be the string '[1, 2, 3, 4, 5]'. Then you replace any blank space-bar ' ' with nothing ''.
Edit:
I think I read your question too quickly and see that you did the exact same as what I have in my code here and said it isn't doing exactly what you want to do. I think the answer here is: no.
As I say in my first paragraph, there is the list and there is the lists representation. The function for the list's representation is a python built-in that can not be trivially overridden. I'm not saying it can't be done, but I don't think you'll get it done without defining some new things.
You can change the print behavior of the list to something you code yourself.
numbers = input().split(',')
for i in range(0, len(numbers)):
numbers[i] = int(numbers[i])
mylist = str(numbers).replace(' ','')
print('[' + ','.join([str(n) for n in numbers]) + ']')
This prints a bracket [, then each number separated by commas without any spaces, and finally the ending bracket ].
Output looks like this:
1, 2, 3, 4, 5
[1,2,3,4,5]
My understanding of your problem is that you want to input a list as a string and want to transform it into a Python list of numbers.
If you input the following string [1, 2, 3, 4, 5], then you can split on , . Then you need to consider removing the leftmost and rightmost character, that correspond to the brackets:
numbers = input()[1:-1].split(', ')
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
print(numbers)
Other options to transform the numbers from strings to integers are the following:
Python built-in map function:
numbers = input()[1:-1].split(', ')
numbers = list(map(int, numbers))
print(numbers)
Python list comprehension:
numbers = input()[1:-1].split(', ')
numbers = [int(n) for n in numbers]
print(numbers)
What you might want to do is create a subclass of list that has the repr implementation you want. That way you can still operate on your list object as you would any other list (e.g. you can access numbers[0] and it will return the first number), but printing the list as a whole will produce the output you're looking for.
class MyList(list):
def __repr__(self) -> str:
return "[" + ",".join(repr(i) for i in self) + "]"
numbers = MyList(int(n) for n in input().split(","))
print(numbers)
print(numbers[0])
Input:
1,2,3,4,5
Output:
[1,2,3,4,5]
1
Since MyList is a list subclass, you can construct one from any iterable, including a generator expression (as in the code above) or an existing list, e.g.:
>>> n_copy = MyList(numbers)
>>> n_copy
[1,2,3,4,5]
You could use the re module's split function to deal with the whitespaces when splitting. Then you just need to join the elements with ',' and embed the whole thing between brackets in the string representation.
import re
numbers = re.split(r'\s*,\s*', input())
print(f"[{','.join(numbers)}]")
How to add commas at required positions in the given string in Python?
In my case, the positions are not fixed.
Example: My requirement is to add the commas after 5th, 8th, 11th, 13th in an input string = "hello Python program"
My expected output would be: hello, Py,tho,n p,rogram
Is there any simplest way to achieve this in Python?
Actually I need to apply a comma on 590 positions in my file record and then process it.
Strings are immutable in python, so if you're going to perform modifications on the string, it would be more efficient to convert the string to a list first. You can then call str.join on the string once you're done.
string = list("hello Python program") # somewhat counterintuitive a name
for i, j in enumerate([5, 8, 11, 13]):
string.insert(i + j, ',')
print(''.join(string))
'hello, Py,tho,n ,program'
>>> string = "hello Python program"
>>> commas = [5, 8, 11, 13]
One way (probably the most efficient):
>>> ','.join(string[i:j] for i, j in zip([None] + commas, commas + [None]))
'hello, Py,tho,n ,program'
Another (for this one, commas should be a set for efficiency):
>>> ''.join(c + ',' * (i in commas) for i, c in enumerate(string, 1))
'hello, Py,tho,n ,program'
Another:
>>> a = list(string)
>>> for i in reversed(commas):
a.insert(i, ',')
>>> ''.join(a)
'hello, Py,tho,n ,program'
Use this function:
def insertc(index,s,c):
return s[:index]+c+s[index:]
s='hello Python program'
j=0
for i in [5,8,11,13]:
s=insertc(i+j,s,',')
j+=1
print(s)
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
When I use "\n" in my print function it gives me a syntax error in the following code
from itertools import combinations
a=[comb for comb in combinations(range(1,96+1),7) if sum(comb) == 42]
print (a "\n")
Is there any way to add new line in each combination?
The print function already adds a newline for you, so if you just want to print followed by a newline, do (parens mandatory since this is Python 3):
print(a)
If the goal is to print the elements of a each separated by newlines, you can either loop explicitly:
for x in a:
print(x)
or abuse star unpacking to do it as a single statement, using sep to split outputs to different lines:
print(*a, sep="\n")
If you want a blank line between outputs, not just a line break, add end="\n\n" to the first two, or change sep to sep="\n\n" for the final option.
Two possibilities:
print "%s\n" %a
print a, "\n"
This will work for you:
I used 1,2...6 in my example and 2 length tuples with a combination sum of 7.
from itertools import combinations
a=["{0}\n".format(comb) for comb in combinations(range(1,7),2) if sum(comb) == 7]
print(a)
for thing in a:
print(thing)
Output
['(1, 6)\n', '(2, 5)\n', '(3, 4)\n']
(1, 6)
(2, 5)
(3, 4)
for me in the past something like print("\n",a) works.
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.