How to remove the last "." from for loop print - python

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

Related

Print without end seperator on last item

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=", ")

How to remove last blank from printed line in python3?

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?

Is there a problem with my string replacement code?

string = input()
for i in range(len(string)):
if i % 3 == 0:
final = string.replace(string[i], "")
print(final)
I was asked the question: "Given a string, delete all its characters whose indices are divisible by 3."
The answer for the input Python is yton. However, my code gives Pyton.
The code makes sense to me but I'm a beginner. Any help?
The problem is that while you are looping, you are overriding the final variable every time the index is divisible by 3.
Instead, try defining the final variable before you start the loop, and add the letters as you loop over them, and only when they their index is NOT divisible by 3 (thus, ignoring the ones where the index IS divisible by 3).
Something like this should work:
string = input()
final = ""
for i in range(len(string)):
if i % 3 != 0:
final += string[i]
print(final)
In your current code, final is used through each iteration of the loop. It continues updating by replacing one character. In each iteration, final is replaced by a different string with one letter from string removed. After the loop has completed, it effectively only replaced one letter, which in this case is "h".
Use this instead (thanks to Mateen Ulhaq for the idea):
print("".join(x for i, x in enumerate(input()) if i % 3 != 0))
string=input()
final=""
for i in range(len(string)):
if i % 3 != 0:
final+=string[i]
print(final)
In your code, the line final = string.replace(string[i], "") would run like this.
Supposing the input is "hellobaby":
i=0, final="ellobaby"
i=3, final="helobaby"
i=6, final="hellobby"

Formatting: multiple print statements without spaces

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

Python Printing and multiplying strings in Print statement

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

Categories