Multiple strings to align - python

So here is my problem, I have this program that is supposed to print multiple lines of numbers according to the number of columns and spaces the user inputs:
def main():
from string import Template # We import the Template method as seen in python glossary 7.1.4
s_num, e_num = [int(x) for x in input("Please enter a starting number and an ending number separated by a comma: ").split(',')] #We define the variables, s_num and e_num, as the respective starting point and ending point of the range that the user will input. In addition we call the int() function to make sure the input is an integer.
column, space = [int(x) for x in input("Please enter the number of numbers printed on a row and the number of spaces per item separated by a comma: ").split(',')] #We define the variables, column and space, as the respective amount of rows and amount of spaces that the user will input. In addition we call the int() function to make sure the input is an integer.
print('------------------------------') # We print a line of indents as in the sample
print('\n')
print ('Your print-out of numbers {}-{} using {} colums and {} spaces between numbers:'.format(s_num, e_num, column, space)) #We use the format method to implement the four variables created in the line and including them in the string phrase.
a = Template('$spce') # We create a variable "a" with one template "spce" that we will modify afterwards to implement in it the number of spaces that the user has inputted.
b = a.substitute(spce = ' ' * (space)) # We create a second variable b that will substitute the template "spce" with the number of spaces, by multipling the integers in the space variable by, ' ', a normal space.
counter = 1 # We create a variable called counter that will count the number of lines, in order to know when to go back to line.
for i in range(s_num,e_num + 1): # We invoke a "for" loop in the range of numbers inputted by the user. In addition we add "+1", to also take the last integer of the range.
print ('{}{}'.format(i,b),end='') # We implement the ".format" method as an alternative to print(i+b) since i and b are from different types, and finally we add " end='' " to get back to the line.
if (counter % column == 0 ): # We invoke a conditional statement, so that the program knows when to get back to the line:
print() # In that respect, if the number of lines divided by the amount of rows is nill: then the program goes back to the line.
counter = counter + 1 # We add an additional line to the counter variable, that is counting the lines, and we iterate all over again until all the numbers are printed
main()
But if i input for instance :
Please enter a starting number and an ending number separated by
a comma: 1,32
Please enter the number of numbers printed on a row and the
number of spaces per item separated by a comma: 10,4
I get :
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32
Rather than :
expected output
I tried the format methods using : {:<},{:-},etc but it works at most for two or three different inputs, rather than all of them.
Thanks in advance

To get the desired output replace
print ('{}{}'.format(i,b),end='')
with
print ('{: >2}{}'.format(i,b),end='')
This is minimal improvement. Here 2 is the amount of digits in the largest number. You should calculate it from e_num value - len(str(e_num)) and use the value to create appropriate string to be formatted and printed:
templ = '{' + ': >{}'.format(len(str(e_num))) + '}{}'
And then use it inside your for loop:
print (templ.format(i,b),end='')

Related

Python, printing multiple string lengths for strings within a list

Using a for loop, how can a list generated by the input function display each string length in the order that they have been input?
example:
Please enter a list of numbers separated by a comma.
one,two,three,four,five
The length of the string one is 3.
The length of the string two is 3.
The length of the string three is 5.
The length of the string four is 4.
The length of the string five is 4.
Below is the code I have written so far. im sure it's laughable but i can't figure it out.
# stringList will contain a list of strings that have been entered.
stringList = input("Please enter a list of numbers seperated by a comma.\ne.g. Citreon,Ford,Audi,Mercedes\n")
i = 0
for i = 0:
print(f"The length of the string {i} is {(len_stringList[])}."
i += 1
I have tried to construct a for loop in order to display the strings in order, along with each strings length.
The string index number should be in text, with index[0] starting at 'one' up to the final user input (five in the example above)
Each string length should be displayed in a numerical value.
Use split to split the input string into a list, and then you can iterate over that list with a for loop and print the len of each element.
>>> for s in input("Please enter a comma-separated list: ").split(","):
... print(f"The length of {s} is {len(s)}")
...
Please enter a comma-separated list: one,two,three,four,five
The length of one is 3
The length of two is 3
The length of three is 5
The length of four is 4
The length of five is 4

Write a function called justify that takes a list of strings and a filed size then returns a single string

Write a function called justify that takes a list of strings and a filed size then returns a single string. The return string will have the original words spaced out in a string of length size. e.g.
justify([“this”, “is”, “a”, “test”],20) à “this is a test”
We are putting 11 characters in a 20 space field, so we have 9 extra spaces. There are 3 places between the words, so we have 3 spaces between each word. If the extra spaces do not divide exactly you can distribute the extra spaces as you like.
'justify([“all”, “too”, “easy”],15) à “all too easy”'
If the field size is too small to add one space between the words then ignore the field size and return the answer with one space between each word.
def justify(x,y):
amount = len(x)-1
final = "".join(x)
ohmy = len(final)
spaces = y - ohmy
real = spaces / amount
print(real)
just = []
length = int(input("length: "))
while True:
hi = input("word: ")
if hi == "end":
break
else:
just.append(hi)
justify(just,length)
This is what I have? Any help?
Seems like you need to
calculate the space taken up by all the words/strings;
find the difference between the limit and the space taken by the words;
divide that difference by the number of gaps between words;
use that result to decide where and how many spaces to put between the words;
construct a string with the words and the spaces.
add logic to check if length of words is greater than field space and react to that

Putting multiple numbers from an input into one list

I'm trying to put multiple interest rates from one input into a list. I'm assuming just putting a comma between them wont separate them into different variables in the list? Is there a way I can get them all into a list in one input or do i need to run the input multiple times and add one each time?
interest_rates_list = []
while True:
investment = input("Please enter the amount to be invested ")
periods = input("Please enter the number of periods for investment maturity ")
if int(periods) < 0:
break
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list.append(interest_rates)
If you input is something like:
4 5 12 8 42
then you can simply split it up by space and assign to values list:
values = input().split()
If your input something like 4,5,12, then you need to use split(',').
You can split the input string into several string and then convert it to float. This can be done in one line.
interest_rates = list(map(float, interest_rates.split(",")))
Here I go a step further, your next move will be to calculate some return based on interest rates, and so you will need float/integer to do so.
The python string function split can accept a delimiter character and split the input string into a list of values delimited by that character.
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list = interest_rates.split(",")
If you take the input, you can convert it to a string by using:
str(interest_rates)
Let this be variable A
So, A = str(interest_rates)
Now, to seperate each entry of the interest rates, we do:
interest_rates_list = A.split(' ')
This function literally splits the string at all spaces and returns a list of all the broken pieces.
NOTE: if you do A.split(*any string or character*) it'll split at the mentioned character. Could be ',' or ';' or ':', etc.
Now you can iter over the newly formed list and convert all the numbers stored as string to ints or floats by doing
for i in interest _rates_list:
i = float(i) #or int(i) based on your requirement

Python Homework - creating a pattern that also has spaces

Problem: Write a program that creates a pattern like the one below. Let the user input a non-negative integer to determine the number of lines of the pattern.
The sample output would take input, then have one blank line, then each next line would have a # (space) #, with increasing amount of spaces as count continues.
Example, entering the number 4 would produce one empty line; two pounds on the second line; one pound, one space, one pound on the third line; one pound, two spaces, one pound on the last line.
lines = int(input("Enter number of lines for pattern: "))
for a in range(lines):
for b in range(a + 1):
print('#', end='')
print()
Above code gives me close to what I want, but it is pounds all across instead of spaces between the two pound signs. I have no idea how to put the spaces there, any help would be awesome.
You can format the output with a variable width:
lines = int(input("Enter number of lines for pattern: "))
for a in range(lines):
print('#%*s' % (a, '#') if a else '')
This outputs:
(blank line)
##
# #
# #
Or try:
for a in range(lines):
print('#%s#' % ((a-1)*' ') if a else '')
Example output:
Enter number of lines for pattern: 4
##
# #
# #

Add a space in between loop outputs using .format: Python 3

I am trying to create a for loop where the user inputs a number n and the output provides the range of values from n to n+6. This needs to all be printed in one row and be right aligned with spaces in between value outputs but no space at the end or start of the output.
So far this is what I've come up with:
n=eval(input("Enter the start number: "))
for n in range(n,n+7):
print("{0:>2}".format(n),end=" ")
However, this results in the following output:
-2 -1 0 1 2 3 4 <EOL>
When the output I want needs to look similar but without the space at the end, like so:
-2 -1 0 1 2 3 4<EOL>
How can I add spaces between values without adding an additional space to the final term?
There are 3 recommendations I could make:
use end="" and insert the whitespaces manually
create a string and print after the loop:
s = ""
for n in range(n, n+7):
s+= str(n)+ " "
s = s[:-1] #remove the ending whitespace
print(s)
which I recommend: Using sys.stdout.write instead print:
print only displays the message after a linebreak was printed. So if there is a long calculation in the loop and there is end=" " you will only see the resulr at the end of all calculations. Use sys.stdout instead
for n in range(n, n+7):
if n < n+7:
sys.stdout.write(str(n)+" ")
else:
sys.stdout.write(str(n))
sys.stdour.flush() #flush output to console
Edit: I evolved a bit and this is what I'd use nowadays:
4. message = " ".join(range(n, n+7))
This puts spaces between all elements of a list. You can choose any separation character instead of a space (or multiple characters).

Categories