I need to print twin primes in the following manner
3:5,5:7,11:13,17:19
But my code is printing like this
3:5,5:7,11:13,17:19,
print("{0}: {1}" .format(n,n+2), end=', ')
I am using end=',' in the print statement and hence the comma at the last.
Is there any other way of printing
Instead of using end make a string first via a join and print that
print(", ".join(f"{n}:{n+2}" for n in my_list))
or you can print the entire list rather than iterating and printing and use sep
print(*(f"{n}:{n+2}" for n in my_list), sep=", ")
Related
for i in range (20):
print(i, end='.')
my result is actually
0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
is there any way or advise so that my print will be
0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19
You can do this:
print(".".join(str(n) for n in range(20)))
That generates the numbers from 0 to 19 (inclusive), converts each one to a string, joins them together with . as a separator, then prints the result.
I would prefer to use the inline "if" statement.
for i in range(20): print(i, end="" if i == 19 else ".")
You can get all elements but the last one. Let's say you have that string on the variable my_str, you could try:
my_str[-1:]
I want to remove the last blank from printed line.
example)
list=[1,2,3,4]
for i in range(2):
print(list[i], end=" ")
>>> 1 2
There is a one blank after '2' in printed line. How can I modify the code to remove the last blank?
You can also use "list unpacking" similar to Unpacking Argument Lists in conjunction with slices.
For example:
print(*list[:2])
Returns:
1 2
+ new line symbol \n
To remove the \n symbol, you can use this code.
print(*list[:2], end="")
You can do this " ".join(map(str, [list[i] for i in range(2)])).
The blank is due to the argument end = " " in print function. This essentially tells the python program to add a " " (blank) instead of newline after every print. So you can either remove it or do something like this in your for loop.
list = [1, 2, 3, 4]
for i in range(2) :
if (i != range(2)[-1]) :
print (list[i], end = " ")
else :
print (list[i], end='')
This tells the python program to not use the extra space or newline at the end of for loop.
You don't need a for loop for this
a=[1,2,3,4]
b=' '.join(map(str,a[:2]))
will do
list=[1,2,3,4]
for i in range(2):
if i == max(range(2)):
print(list[i])
else:
print(list[i], end=" ")
1 2
If you mean you always want to cut the last space but keep the others, how about adding if?
I'm trying to print multiple things scattered in a loop. Here is an example:
print str(n)+" ",
for I in range(k):
print str(l)+"+",
if l>4:
break
This gives me an out put like
10= 1+ 2+ 3+ 4
While I want it to give
10=1+2+3+4
Use sys.stdout.write directly instead of print:
from sys import stdout
stdout.write(str(n)+" ")
for I in range(k):
stdout.write(str(l)+"+")
if l>4:
break
The reason this happens is because a comma with the print statement forces a space between the two elements. You're best to construct the target output string inside the loop, then print it once. Try to avoid any sort of output being done in a loop if possible.
outstr = str(n)+" " # do you mean `str(n)+"="?`
for I in range(k):
outstr = outstr + str(l)+"+",
if l>4:
break
print outstr
I am trying to write a simple python program that prints two ##, then # #, and increases the number of spaces in between the #'s each time. Here is the code I tried:
i=0
while (i<=5):
print ("#" (" " * i) "#")
#print (" " * i)
#print ("#" "#")
The multiplication works in the first line of code I tested then commended out, I see it in the shell each time it prints one more space.
Printing two #'s works also.
I can't figure out how to combine it into one statement that works, or any other method of doing this.
Any help would be appreciated, thanks.
i=0
while (i<=5):
print( "#" +(" "*i)+ "#")
i=i+1
You need to add the strings inside the print statement and increment i.
You want to print a string that depends an a variable. There are other methods to build a string but the simplest, most obvious one is adding together some fixed pieces and some computed pieces, in your case a "#", a sequence of spaces and another "#". To add together the pieces you have to use the + operator, like in "#"+" "+"#".
Another problem in your code is the while loop, if you don't increment the variable i its value will be always 0 and the loop will be executed forever!
Eventually you will learn that the idiom to iterate over a sequence of integers, from 0 to n-1 is for i in range(n): ..., but for now the while loop is good enough.
This should do it:
i=0
while (i<=5):
print ('#' + i * ' ' + '#')
i = i + 1
Try this:
def test(self, number: int):
for i in range (number)):
print('#' +i * ''+ '#')
i+=1
return
it's a loop to reverse a string entered by the user, it reads letters in reverse and put them into a sentence. the problem is that, for example user's input is hello, the comma(,) in the last line of the code makes the output to be o l l e h, but if there isnt a comma there, the output will have each letter in a line. and concatenate (+) doesnt work it gives an error. What do i do so that the output would be olleh instead of o l l e h?
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
for index in range (end,-1,-1):
print phrase[index],
how about:
string = ''
for i in range(end, -1, -1):
string += phrase[i]
print string
However, an easier, cleaner way without the for loop is:
print phrase[::-1] # this prints the string in reverse
And also there is:
#As dougal pointed out below this is a better join
print ''.join(reversed(phrase))
#but this works too...
print ''.join(phrase[i] for i in range(end, -1, -1)) # joins letters in phrase together from back to front
To concatenate something, you have to have a string to concatenate to. In this case, you need a variable that is defined outside of the for loop so you can access it from within the for loop multiple times, like this:
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
mystr = ""
for index in range (end,-1,-1):
mystr += phrase[index]
print mystr
Note that you can also simply reverse a string in Python doing this:
reversedstr = mystr[::-1]
This is technically string slicing, using the third operator to reverse through the string.
Another possibility would be
reversedstr = ''.join(reversed(mystr))
reversed returns a reversed iterator of the iterator you passed it, meaning that you have to transform it back into a string using ''.join