For example, if I had a range of 10, it would print:
9
8
7
and so on. Then when I have double digits, so with a range of 11, it prints out:
10
9
8
But, I want it to print out with the 9 under the 0 instead. Any way to do this?
You could use str.rjust:
for i in reversed(range(1, 11)):
print(str(i).rjust(2))
Output:
10
9
8
7
6
5
4
3
2
1
In Python 3:
for i in range(11)[::-1]:
print(f"{i:>2}")
If you want three-digit numbers, change the 2 to a 3.
You can just add a space at the beginning of the number.
I just calculate the amount of digits and pad the lower number with spaces
max = 1337
max_len = len(str(max))
for i in reversed(range(max)):
str_len = len(str(i))
if max_len > str_len:
difference = max_len - str_len #calculate amount of needed spaces
print(" " * difference + str(i)) #pad string with spaces
else:
print(i)
Related
Use nested for loops to create the following printout:
The number of rows should be read from the user. Use formatted printouts
so that the numbers are aligned even for two-digit numbers.
• All printed numbers correspond to column numbers.
• No number is printed if the column number is less than the row number.
• Print a suitable number of spaces to fill an empty column.
# Program to print a pattern with numbers
print("Program to print a pattern with numbers ")
print("-" * 50)
n = int(input("Please enter the number of rows "))
print("-" * 50)
for i in range(n + 1):
# Increase triangle hidden
for j in range(i):
print(" ", end=' ')
# Decrease triangle to include numbers in pattern not in increment
for j in range(i, n):
print(j + 1, end=" ")
print()
The code above produces the required output but the numbers are not aligned in an input with 2 digits. How do I format the iterables to make a perfectly aligned output printout.
Output:
This is how you might modify your code to use str.rjust. Adjust the 2 in rjust(2) to whatever number you want.
print("Program to print a pattern with numbers ")
print("-" * 50)
n = int(input("Please enter the number of rows "))
print("-" * 50)
for i in range(n + 1):
# Increase triangle hidden
for j in range(i):
print(" ".rjust(2), end=" ")
# Decrease triangle to include numbers in pattern not in increment
for j in range(i, n):
print(str(j+1).rjust(2), end=" ")
print()
For your example, this gives:
Program to print a pattern with numbers
--------------------------------------------------
Please enter the number of rows 12
--------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12
2 3 4 5 6 7 8 9 10 11 12
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12
5 6 7 8 9 10 11 12
6 7 8 9 10 11 12
7 8 9 10 11 12
8 9 10 11 12
9 10 11 12
10 11 12
11 12
12
You can use str.rjust to right-justify a string. As long as you know the overall length of each line, that makes it easy to align each line so that they're all aligned on the right:
>>> n = 5
>>> for i in range(1, n+1):
... print(''.join(str(j).rjust(3) for j in range(i, n+1)).rjust(n*3))
...
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
i can't understand this convention range in python, range(len(s) -1) for representing all elements including the last one. For me makes no sense like when I print all elements the last one is not included in the list. Someone could help me understand this logic?
this>
s = "abccdeffggh"
for i in range(len(s) -1):
print(i)
result this
0
1
2
3
4
5
6
7
8
9
you are trying to print range to compiler you saying like this print numbers greter than 1 and below than 10 to the output not include 1 and 10 compiler only print 2,3,4,5,6,7,8,9 in your case
s = "abccdeffggh"
this s string length must be 11 if you print like this
s = "abccdeffggh"
for i in range(len(s)):
print(i)
you get output as 1,2,3,4,5,6,7,8,9,10 that is the numbers between 0 and 11
but in your code you have subtract -1 from the length then your range is become -1 and 10 then compiler print all numbers between the -1 and 10 it not include -1 and 10
try this code
s = "abccdeffggh"
print(len(s))
print(len(s)-1)
for i in range(len(s)):
print(i)
I have a string of 6400 numbers which I want to put into an 80x80 string format, for example
string1 = '1 2 3 4 5 6 7 8 9'
What I'm trying to do is this:
string2 = '''1 2 3
4 5 6
7 8 9'''
*the numbers are different lengths too
I have tried using split() but I don't know how to 'count' the amount of spaces and put it into one large string
You can split on space and iterate through it making chunks of given size:
string1 = '1 2 3 4 5 6 7 8 9'
size = 3
splits = string1.split()
print('\n'.join(' '.join(splits[j] for j in range(i, i+size)) for i in range(0, len(splits), size)))
# 1 2 3
# 4 5 6
# 7 8 9
Variable-length numbers? Just use regex.
import re
string1 = '1 22 333 4444 55555 666666 77777777 888888888 9999999999'
string2 = '\n'.join(re.findall('((?:\S+ ){2}\S+)', string1))
The (?:) makes a group you can repeat but doesn't capture it in the match, which makes the direct join possible. Without it, you'd get tuples.
A re.sub would also work.
string2 = re.sub('((\S+ ){2}\S+) ', lambda m: m.group()+'\n', string1)
You would use a {79} instead of the {2} of course, which repeats the '\S+ ' pattern (one or more non-whitespace characters followed by a space) so you don't have to write it out.
You could do this by slicing the string by a set chunk size
# Print a new line every 6 characters
# Change this as needed
chunk_size = 6
# The string to split
s = '1 2 3 4 5 6 7 8 9'
# Iterate over a range of numbers 0 to the length of the string
# with a step size of `chunk_size`
# With `chunk_size` as 6, the range will look like
# [0, 6, 12]
for i in range(0, len(s), chunk_size):
# Slice the string from the current index
# to the current index plus the chunk size
# ie: [0:6], [6:12], [12:18]
print(s[i:i+chunk_size])
print()
# To do this with list comprehension
s2 = "\n".join(s[i:i+chunk_size] for i in range(0, len(s), chunk_size))
print(s2)
# Ouptut:
# 1 2 3
# 4 5 6
# 7 8 9
Or if you have variable length numbers, do as Austin said, and apply the same concept on a split version of the string
chunk_size = 3
s = '10 20 30 4 5 6 7 8 9'.split()
for i in range(0, len(s), chunk_size):
print(" ".join(s[i:i+chunk_size]))
print()
s2 = "\n".join(" ".join(s[i:i+chunk_size]) for i in range(0, len(s), chunk_size))
print(s2)
# Output:
# 10 20 30
# 4 5 6
# 7 8 9
Please close if this is a duplicate, but this answer does not answer my question as I would like to print a list, not elements from a list.
For example, the below does not work:
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(%3s % mylist)
Desired output:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
Basically, if all items in the list are n digits or less, equal spacing would give each item n+1 spots in the printout. Like setw in c++. Assume n is known.
If I have missed a similar SO question, feel free to vote to close.
You can exploit formatting as in the example below. If you really need the square braces then you will have to fiddle a bit
lst = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
frmt = "{:>3}"*len(lst)
print(frmt.format(*lst))
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
items=range(10)
''.join(f'{x:3}' for x in items)
' 0 1 2 3 4 5 6 7 8 9'
If none of the other answers work, try this code:
output = ''
space = ''
output += str(list[0])
for spacecount in range(spacing):
space += spacecharacter
for listnum in range(1, len(list)):
output += space
output += str(list[listnum])
print(output)
I think this is the best yet, as it allows you to manipulate list as you wish. even numerically.
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(*map(lambda x: str(x)+" ",a))
I'm trying to print a half pyramid that stars on the left side in python.
So far, this is my code
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in range(1, i):
print(j, end = " " )
print("\n")
and my output is
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
However, my output is meant to be in the opposite order:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How can I make this change?
Just reverse the second loop -- the one that prints that actual numbers:
for j in range(i-1, 0, -1):
The last parameter controls the "step", or how much the variable changes on each loop iteration. Output:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
...
Reverse the range by adding the third argument (-1). Also format your numbers to use 2 places, so 10 is not pushing the last line to the right. Finally, the last print should probably not have \n, since that is already the default ending character of print:
for i in range(1,12):
for j in range(12 - i):
print(" ", end = "")
for j in range(i-1, 0,-1):
print(str(j).rjust(2), end = "" )
print()
You could just reverse the range that you print out as numbers
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in reversed(range(1, i)):
print(j, end = " " )
print("\n")
The problem is in your second for loop, as you are looping from 1 to i, meaning you start off with 1 being printed first, and every following number until (not including) i.
Fortunately, for loops are able to go in reverse. So, instead of:
for j in range(1, i)
You could write:
for j in range((i-1), 0, -1)
Where the first parameter is signifies where the loop starts, the second is where the loop finishes, and the third signifies how large our jumps are going to be, in this case negative. The reason we are starting at i-1 and finishing at 0 is because loops start at exactly the first given number, and loop until just before the second given number, so in your given code the loop stops just before i, and so this one starts just before i as well, although you could remove the -1 if you wish to include 12 in the pyramid.