new line with variable in python - python

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.

Related

Prevent trailing comma when printing comma-separated dictionary items [duplicate]

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");

remove spaces/commas from a variable to add to a string

I need it to look like
https://doorpasscode.kringlecastle.com/checkpass.php?i= (3333)&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c
instead it looks like
https://doorpasscode.kringlecastle.com/checkpass.php?i= (3, 3, 3, 3)&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c
Code:
for i in range(0, 4):
for j in range(0, 4):
for k in range(0, 4):
for l in range(0, 4):
trypass=(i,j,k,l)
#print(i,j,k,l, sep='')
print('https://doorpasscode.kringlecastle.com/checkpass.php?i= {}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(trypass).strip(','))
strip only strips from the beginning and end of the string, it doesn't strip the characters from the middle.
Your problem isn't really stripping, it's adding unnecessary junk in the first place by directly stringifying the tuple.
To fix both, convert trypass to a string up front with no joiner characters in the middle:
trypass = ''.join(map(str, (i,j,k,l)))
A side-note: You could shorten this a lot with itertools.product to turn four loops into one (no arrow shaped code), and avoid repeatedly stringifying by converting the range elements to str only once, directly generating trypass without the intermediate named variables:
from itertools import product
for trypass in map(''.join, product(map(str, range(0, 4)), repeat=4)):
print('https://doorpasscode.kringlecastle.com/checkpass.php?i= ({})&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(trypass).)
.format(trypass) will format the tuple as a string using the default tuple formatting rules, e.g. (3, 3, 3, 3). Instead you should explicitly tell it how to format the string, like:
.format(''.join(str(i) for i in trypass))
You have a tuple that you want to reduce to a string.
>>> trypass = (3,3,3,3)
>>> ''.join(str(i) for i in trypass)
'3333'
Or, since you know there are exactly 4 digits,
print('https://doorpasscode.kringlecastle.com/checkpass.php?i={}{}{}{}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(*trypass))
Or, just iterate over the 4-digit numbers directly. itertools.product can generate the tuples for you.
import itertools
for trypass in itertools.product("0123", repeat=4):
print('https://doorpasscode.kringlecastle.com/checkpass.php?i={}{}{}{}&resourceId=77af125f-213f-4b2b-9e1e-ce156b6a838c'.format(*trypass))

How to add commas at required positions in the given string in Python?

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)

How i can remove space between integer between brakets in python

i have a problem i want to submit it on online judge it want me to print the result in co-ordinates x,y like
print (2,3)
(2, 3) # i want to remove this space between the , and 3 to be accepted
# i want it like that
(2,3)
i make it with c++ but i want python i challenge my friends that python make any thing please help me
the whole code of proplem i work on it
Bx,By,Dx,Dy=map(int, raw_input().split())
if Bx>Dx:
Ax=Dx
Ay=By
Cx=Bx
Cy=Dy
print (Ax,Ay),(Bx,By),(Cx,Cy),(Dx,Dy) #i want this line to remove the comma between them to print like that (Ax,Ay) not that (Ax, Ay) and so on the line
else:
Ax=Bx
Ay=Dy
Cx=Dx
Cy=By
print (Ax,Ay),(Dx,Dy),(Cx,Cy),(Bx,By) # this too
you can use format:
>>> print "({},{})".format(2,3)
(2,3)
your code should be like this:
print "({},{})({},{}),({},{}),({},{})".format(Ax,Ay,Bx,By,Cx,Cy,Dx,Dy)
To do this in the general case, manipulate the string representation. I've kept this a little too simple, as the last item demonstrates:
def print_stripped(item):
item_str = item.__repr__()
print item_str.replace(', ', ',')
tuple1 = (2, 3)
tuple2 = (2, ('a', 3), "hello")
tuple3 = (2, "this, will, lose some spaces", False)
print_stripped(tuple1)
print_stripped(tuple2)
print_stripped(tuple3)
My space removal is a little too simple; here's the output
(2,3)
(2,('a',3),'hello')
(2,'this,will,lose some spaces',False)
"Strip" the tuple whitespace with listcomprehension;
tuple_ = (2, 3)
tuple_ = [i[0] for i in tuple]
in function
def strip_tuple(tuple_):
return [i[0] for i in tuple_]

Converting lists of tuples to strings Python

I've written a function in python that returns a list, for example
[(1,1),(2,2),(3,3)]
But i want the output as a string so i can replace the comma with another char so the output would be
'1#1' '2#2' '3#3'
Any easy way around this?:)
Thanks for any tips in advance
This looks like a list of tuples, where each tuple has two elements.
' '.join(['%d#%d' % (t[0],t[1]) for t in l])
Which can of course be simplified to:
' '.join(['%d#%d' % t for t in l])
Or even:
' '.join(map(lambda t: '%d#%d' % t, l))
Where l is your original list. This generates 'number#number' pairs for each tuple in the list. These pairs are then joined with spaces (' ').
The join syntax looked a little weird to me when I first started woking with Python, but the documentation was a huge help.
You could convert the tuples to strings by using the % operator with a list comprehension or generator expression, e.g.
ll = [(1,1), (2,2), (3,3)]
['%d#%d' % aa for aa in ll]
This would return a list of strings like:
['1#1', '2#2', '3#3']
You can concatenate the resulting list of strings together for output. This article describes half a dozen different approaches with benchmarks and analysis of their relative merits.
' '.join([str(a)+"#"+str(b) for (a,b) in [(1,1),(2,2),(3,3)]])
or for arbitrary tuples in the list,
' '.join(['#'.join([str(v) for v in k]) for k in [(1,1),(2,2),(3,3)]])
In [1]: ' '.join('%d#%d' % (el[0], el[1]) for el in [(1,1),(2,2),(3,3)])
Out[1]: '1#1 2#2 3#3'
[ str(e[0]) + ',' + str(e[1]) for e in [(1,1), (2,2), (3,3)] ]
This is if you want them in a collection of string, I didn't understand it if you want a single output string or a collection.
[str(item).replace(',','#') for item in [(1,1),(2,2),(3,3)]]
You only need join and str in a generator comprehension.
>>> ['#'.join(str(i) for i in t) for t in l]
['1#1', '2#2', '3#3']
>>> ' '.join('#'.join(str(i) for i in t) for t in l)
'1#1 2#2 3#3'
you could use the repr function and then just replace bits of the string:
>>> original = [(1,1),(2,2),(3,3)]
>>> intermediate = repr(original)
>>> print intermediate
[(1, 1), (2, 2), (3, 3)]
>>> final = intermediate.replace('), (', ' ').replace('[(','').replace(')]','').replace(', ','#')
>>> print final
1#1 2#2 3#3
but this will only work if you know for certain that none of tuples have the following character sequences which need to be preserved in the final result: ), (, [(, )], ,

Categories