I'm trying to print a multiline string in a "for" loop. The problem is I'd like to have the output printed all on the same lines. Example:
for i in range(5):
print('''
{a}
|
{b}
'''.format(a=i,b=i+1))
The output looks like:
0
|
1
1
|
2
2
|
3
3
|
4
4
|
5
Instead I'd like it to be:
0 1 2 3 4
| | | | |
1 2 3 4 5
​But I can't get how to do it. Thanks for the help.
Try with list concaternation:
x = 5
print (" ".join(str(i) for i in range(x)))
print ('| '*x)
print (" ".join(str(i) for i in range(1,x+1)))
import sys
myRange = range(5)
for i in myRange:
sys.stdout.write(str(i))
print()
for i in myRange:
sys.stdout.write('|')
print()
for i in myRange:
sys.stdout.write(str(i+1))
print()
You need sys.stdout.write to write without \n. And this code will not work if you have range more than 9 (10+ has 2+ chars, so you need special rules for spaces before |).
Just to throw in a fun (but bad, don't do this) answer:
for i in range(5):
print('{}\033[1B\033[1D|\033[1B\033[1D{}\033[2A'.format(i, i+1), end='')
print('\033[2B')
This uses terminal control codes to print column by column rather than row by row. Not useful here but something that's good to know about for when you want to do weirder terminal manipulation.
You can only print one line at a time. So first you'll have to print the line with all the a elements, then the line with all the bars, and finally the line with all the b elements.
This can be made easier by first preparing every line before printing it:
line_1 = ""
line_2 = ""
line_3 = ""
for i in range(5):
line_1 += str(i)
line_2 += "|"
line_3 += str(i+1)
print(line_1)
print(line_2)
print(line_3)
There are of course many ways with the same basic idea. I picked the one that is (IMHO) easiest to understand for a beginner.
I didn't take spacing into account and once you do, it gets beneficial to use lists:
line_1_elements = []
line_2_elements = []
line_3_elements = []
for i in range(5):
line_1_elements.append(str(i))
line_2_elements.append("|")
line_3_elements.append(str(i+1))
print(" ".join(line_1_elements))
print(" ".join(line_2_elements))
print(" ".join(line_3_elements))
Similar to Tim's solution, just using map instead of the genrators, which I think is even more readable in this case:
print(" ".join(map(str, range(i))))
print("| " * i)
print(" ".join(map(str, range(1, i+1))))
or alternatively, less readable and trickier, a heavily zip-based approach:
def multi(obj):
print("\n".join(" ".join(item) for item in obj))
r = range(6)
multi(zip(*("{}|{}".format(a, b) for a, b in zip(r, r[1:]))))
What's your goal here? If, for example, you print up to n>9, your formatting will be messed up because of double digit numbers.
Regardless, I'd do it like this. You only want to iterate once, and this is pretty flexible, so you can easily change your formatting.
lines = ['', '', '']
for i in range (5):
lines[0] += '%d ' % i
lines[1] += '| '
lines[2] += '%d ' % (i+1)
for line in lines:
print line
Related
I need help making a mirrored right triangle like below
1
21
321
4321
54321
654321
I can print a regular right triangle with the code below
print("Pattern A")
for i in range(8):
for j in range(1,i):
print(j, end="")
print("")
Which prints
1
12
123
1234
12345
123456
But I can't seem to find a way to mirror it. I tried to look online on how to do it but I can't seem to find any results for python and only examples for Java.
Here is one using the new f-string formatting system:
def test(x):
s = ""
for i in range(1,x+1):
s = str(i) + s
print(f'{s:>{x}}')
test(6)
Something like this works. I loop over the amount of lines, add the whitespace needed for that line and print the numbers.
def test(x):
for i in range(1,x+1):
print((x-i)*(" ") + "".join(str(j+1) for j in range(i)))
test(6)
I am trying to remove the spaces that appear after the output of the code. I have tried to use the .rstrip but it doesn't seem to work.
The coding is:
msg = Tjghksikdsiiireskfafslweicfnareodorffqecproerdtre
var1 = 0
var2 = 1
for i in range(len(msg)):
print(msg[var1:var2], end=' ')
var1 = int(var1) + 3
var2 = int(var2) + 3
It produces the correct coding apart from that it has lots of extra spaces at the end. Is there a way to fix this?
The output produces:
T h i s i s a l i n e o f c o d e
like it is supposed to but it adds alot of spaces after. Please help.
the extra spaces are because you are trying to print every third character but it is repeating once for every character, you can just change your for loop to this:
for i in range( int(len(msg) /3) +1):
I need to make a program in Python 3 which outputs the numbers that are not repeted given a sequence of numbers, I have done this so far:
a = list(map(int,input().split()))
for i in a:
if a.count(i) == 1:
print(i,end=" ")
The problem is, if you type the following sequence "4 3 5 2 5 1 3 5", the output will be "4 2 1 " instead of "4 2 1" ( Which was the expected result). My question is, Is there a way to make the "end" argument not to print an extra space at the end?
Thank you,
In that case you better do not let the print(..) add the spaces, but work with str.join instead:
print(' '.join(str(i) for i in a if a.count(i) == 1))
The boldface part is a generator, it yields the str(..) of all the is in a where a.count(i) == 1. We then join these strings together with the space ' ' as separator.
Here print will still add a new line, but we can use end='' to disable that:
print(' '.join(str(i) for i in a if a.count(i) == 1), end='')
I'm trying to create a iso triangle (one that starts in the middle).
I have a code but the problem is that I'm not allowed to use Y* "*" 5 in my code.
(The y is a variable there)
Also I may only use one print statement at the end of my code.
Can you please help me out.
f = int(raw_input("enter"))
for i in range(f):
print " " * (f-i-1) + "*" * (2*i+1)
creats this triangle
*
***
*****
*******
*********
***********
However, you are not allowed to use the *-operator on string and int. So for example ''***'' * 3 is not allowed, but 3 * 4 is
This just creates a continuous string and then prints it at the end
f = int(raw_input("Enter height: "))
s = ''
for i in xrange(f):
for j in xrange(f-i-1):
s += ' '
for j in xrange(2*i+1):
s += '*'
s += '\n'
print s
This is a solution which i think is very easy to understand. You can make the parameter of range() variable, to make it more dynamic.
from __future__ import print_function
for i in range(1,12,2):
count=(11-i)/2
for j in xrange(count):
print(" ",end='')
for j in xrange(i):
print("*",end='')
for j in xrange(count):
print(" ",end='')
print(end="\n")
I think the best solution is using the center() string method:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
star += "**" if X>0 else ""
full_string += star.center(2*f-1) + "\n"
print full_string[:-1]
The str.center() documentation:
https://docs.python.org/2/library/string.html#string.center
EDIT: If you can't use the print statement within the for loop, you could concatenate the string during the loop and print it at the end:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
# the first row should take only one star
star += "**" if X>0 else ""
star2 = star.center(2*f-1)
full_string += star2 + "\n"
# slice the string to delete the last "\n"
print full_string[:-1]
I noticed that using a for loop add a newline character. If you want to avoid this, you can slice the string before printing.
There is no problem with this code, i just checked it and it worked fine. If you would post the error message we might be able to help a bit more.
I'm finishing up an assignment for my 1035 computer science lab and the last thing I need to do is arrange inputted numbers in a diagonal line.
I've tried things like:
print (\tnum2)
and like this:
print ('\t'num2)
but I can't figure out how to do it. I've looked through my programming book, but have been unable to find an explanation on how to do it.
strings in python can be concatenated using the + sign. For example
print(' ' + str(a))
will give the following output for a=1
1
Notice the single blank space before 1. The function str(a) returns the integer a in string format. This is because print statement can only print strings, not integers.
Also
print(' ' * i)
prints i blank spaces. If i = 10, then 10 blank spaces will be printed.
So, the solution to the question can be:
a = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(a)):
print((' ' * i) + str(a[i]))
Here's a simple example that prints items in a list on a diagonal line:
>>> l = [1,2,3,4,5]
>>> for i in range(len(l)):
... print("\t" * i + str(l[i]))
...
1
2
3
4
5
You can also do it using .format
nome = input("nome:")
a = " "
b = len(nome)
for i in range(b):
print ("{0} {1}".format(a * i, nome[i]))
print ("\n next \n")
c=b
for i in range(b):
print ("{0} {1}".format(a * c, nome[i]))
c = c-1
this give diagonal increasing or decreasing