Here is my code at the moment
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
and the output looks like this
Percent off: 5
Percent off: 10
Percent off: 15
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
My question is focusing on this part
Percent off: 5%
10%
15%
20%
I'm struggling to figure out how to only print the Percent off: part once in my for loop.
I really dislike teachers who tell students to accomplish something without having shown them the right tool for the job. I'm guessing you haven't yet been introduced to the string.format() method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver.
Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So:
poff = 'Percent off: '
pad = ' '*len(poff)
p = poff
for percentage in percentagesOff:
print(p ,percentage, end= " ")
p = pad # for all subsequent trips around the loop
Better style would be to allow for the possibility that you might want poff output again (say) at the top of each page of output. So a better way to do the second code block is
for lineno, percentage in enumerate(percentagesOff):
if lineno==0: # can replace later with are-we-at-the-top-of-a-page test?
p = poff
else
p = pad
# p = poff if lineno==0 else pad # alternative shorter form
print(p ,percentage, end= " ")
You can just pull it out of the for loop, then it gets printed only once, or you could "remember" that you already printed it by setting some boolean variable to True(initialized at False) and then checking whether that variable is True or False before printing that part of the string.
Here
percentagesOff = [5, 10, 15, 20]
print("Percent off:\t", percentagesOff[0], '%')
for percentage in percentagesOff[1:]:
print("\t\t", percentage, "%")
Output
Percent off: 5 %
10 %
15 %
20 %
Here is one alternate solution:
percentagesOff = [1,2,3,4,5,6,7,8,9,10]
print 'Percent off: ', percentagesOff[0] #use blanks instead of '\t'
for percentage in percentagesOff[1:]:
print ' '*len('Percent off: '), percentage
The last line, leaves one blank space for every character of the string ''Percent off: '' and then start printing elements of array.
Basically, "len('something')" returns how many character does the string 'something' include. Then we muliply ' ' (which is one space) by that number.
It is interesting excercise......
You can do something like this.
first = True
for p in pe:
if first == True:
print("percent off: ")
first = False
print(p)
else:
....
....
But you would not normally do it this way.
The fact is that python print add line break after your string to be printed. So,
Import import sys and, before your loop, use that:
sys.stdout.write(' $10 $100 $1000\n')
sys.stdout.write('Percent off:')
And now, you can start using print to write your table entries.
You can simply add a if statement with a boolean too.
Related
I'm having a tough time finding the exact wording for my question since I'm new to formatting strings.
Let's say I have two variables:
customer = 'John Doe'
balance = 39.99
I want to print a line that 25 characters wide, and fills the space between the two values with a specific character (in this case, periods):
'John Doe .......... 39.99'
So as I loop through customers, I want to print a line that is always 25 characters, with their name at the left, and their balance at the right, and allow the periods to adjust to fill the space between.
I can break this into multiple steps and accomplish the result...
customer = 'Barry Allen'
balance = 99
spaces = 23 - len(customer + str(balance))
'{} {} {}'.format(customer, '.' * spaces, balance)
# of course, this assumes that len(customer + str(balance)) is less than 23 (which is easy to work around)
...but I'm curious if there is a more "elegant" way of doing it, such as with string formatting.
Is this even possible?
Thanks!
You can use ljust() and rjust() of string objects in python:
customer = 'John Doe'
balance = 39.99
output = customer.ljust(15, '.') + str(balance).rjust(10, '.')
print(output)
#John Doe............39.99
Depending on format you need, you can tune it with changing the widths or adding space characters.
If you did not want to have spaces on either side of the dots as the other answer would suggests, you can achieve that specifying formatting just as well:
"{:.<17s}{:.>8.2f}".format(customer, balance)
Would do 17 characters wide left aligned, . right padded string and 8 characters of right aligned, . left padded, float with precision of 2 decimal points.
You can do that same with an f-string (Python >=3.6):
f"{customer:.<17s}{balance:.>8.2f}"
However, if you also want to include the space on either side of the dots, it gets trickier. You can still do that, but you need to double pad / format or concatenate before filling in the gap:
"{:.<16s}{:.>9s}".format(f"{customer} ", f" {balance:>.2f}")
But I would be somewhat at pain to call that more elegant.
You could also do all that with formatting:
# Fill in with calculated number of "."
"{} {} {:.2f}".format(customer,
"."*(25 - (2 + len(customer) + len(f"{balance:.2f}"))),
balance)
# Similarly used for calculated width to pad with "."
"{} {:.^{}s} {:.2f}".format(customer,
"",
25 - (2 + len(customer) + len(f"{balance:.2f}")),
balance)
But again, more elegant is it really not.
I need help to see what is wrong with my code; I'm getting the incorrect output.
I need the output to print the first initial and last name (with a period . in front of the first initial), for example: "Anna Lockswell" should be printed as "A. Lockswell".
So far I have:
firstName = input("What is your first name? ")
lastName = input("What is your last name? ")
str(print(firstname[0:-1], +lastname))
Welcome to programming! There are a few issues with what you've posted. First, let's try to get the first letter of firstname:
firstname = input("What is your first name? ")
# firstname is a string, where each letter acts like an element in an array
# to get the first letter, do this:
first_initial = firstname[0]
Per Micha's suggestion, the reason I'm using firstname[0] is because I only want the first letter. The slice firstname[0:-1] will give you everything except the last letter, which isn't quite what you want.
Now, you already have your lastName, next to print.
You have str(print("thing to print")). The problem here is print is a function which doesn't return anything. By wrapping that in str you will see the output None. To print, just call print:
print(first_initial + '.' + ' ' + lastName)
You will need to add a space to the printed output to space out the initial and the last name. There are fancier and more pythonic ways to print, but I feel that this is a sufficient place to start
here are a few things that need attention:
when you write firstname[a:b] it'll return the value of
firstname from char a to char b. so when your firstname is
"anna" and you'll type firstname[1:3] you'll get 'nn'. in this case minus one is equal to the index of the last character which is 3. so firstname[0:-1] will return "ann". in your case it should be changed to firstname[0].
str in the last line is completely unnecessary. str is used for converting other types to string. for example str(1) returns '1'.
print(a,b) will print 2 3 assuming a = 2 and b = 3 so you'll need to use print( a + '.' + b) for getting 2.3. ( there are many other ways to do this).
Try any of these:
>>> print('{}. {}'.format(firstname[0], lastname))
A. Lockswell
>>> print(firstname[0] + '. ' + lastname)
A. Lockswell
>>> print(f'{firstname[0]}. {lastname}')
A. Lockswell
I am in an introduction to Anaconda class and I need to write a program to determine how many times a dice roll(s) land on a certain amount of faces. However, I cannot get it to print my answer correctly.
Your problem is your print statement. You try to print a string then something called end then another string, and so forth. I think you want that end to be an end-of-line character.
Instead of printing something like
print("a string" end "another string" end "a third string")
use
print("a string\n" "another string\n" "a third string")
Note that "\n" is the end-of-line character in Python. My code also uses a feature of Python where you can combine string literals by placing them next to each other. Let lets you see the individual lines more clearly. Your code failed because you tried to do this with a string variable, namely end, and you did not even define that variable.
From Python docs: https://docs.python.org/3/library/functions.html#print
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
As you can see, the end is one of the parameters for the print() function, and by default, end=’\n’. So to use it correctly, you just have to change the end variable (which may not be directly applicable to your code)
Here are some examples:
>>> for i in range(3):
print(i, end =' ')
0 1 2
>>> for i in range(3):
print(i, end ='')
012
>>> for i in range(3):
print(i) # by default end=\n
0
1
2
>>>
And also, if I am understanding your logic correctly, the same code can be re-written as such.
import random
RollDice = int(input("Number of Rolls:"))
numbers = [0 for _ in range(6)] # array of 6 spaces with int 0
for i in range(RollDice):
Roll = random.randint(1,6)
numbers[Roll-1] += 1 # the array index starts from 0 hence you need Roll-1
plusMinus = "+-----"*6 + "+\n" # since you are repeating this you might want to assign it to a variable
print(plusMinus + "| 1 | 2 | 3 | 4 | 5 | 6 |\n" + "| " + " | ".join(map(str,numbers)) + " |\n" + plusMinus)
P.S. Rather than attaching an image, please copy and paste your code next time, so that we can copy n paste to test.
My current code
defname,last_name):
if not isinstance(reg, int) or \
not isinstance(year, int) or \
not isinstance(degree, str) or \
not isinstance(other_name, str) or \
not isinstance(last_name, str) :
print("Invalid string argument")
elif 0<=year<=4:
l.append((reg,year,degree,other_name,last_name))
else: print("Invalid year")
def p
reg,year,degree,other_name,last_name = student.strip().split(" ",4)
reg=int(reg)
year=int(year)
fullName=last_name+ ", " + other_name
thisYear="Year " + str(year)
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s"),format(thisYear,">6s"))
how can I do this effectively with the right formats? I am trying to make it so it uses both functions and is checking for valid
Well, for the reason it's printing on that side, that's because of the way you called .split(). Calling it with the 4 will of course restrict it to splitting 4 times. And since it splits from left to right, once it has made its 4th split (ie. after 'Homer'), it will simply return the rest of the string as a whole (ie. 'J Simpson').
If I were you, I would do it like this:
reg,year,degree,*name = student.strip().split(" ")
name = list(reversed(name))
fullname = name[0] + ', ' + ' '.join(name[1:])
Doing *name lets you grab multiple tokens as a list, and then process them however you like.
First off, wouldn't you want it to print Simpson, Homer J?
Secondly, it prints it J Simpson, Homer because this is what your list looks like:[1342347, 2, G401, Homer, J Simpson].
It splits it this way because you told it to split at each space it sees, and to make a maximum of 4 separate strings. It doesn't know that middle names belong to other_name, so you have to do a little more work in your string parsing to get that to behave as desired.
This is because you are limiting the number of splits to 4.
Thus, for the third line, the 4th space that gets split is between "Homer" and "J". Thus, "J" and "Homer" are in the same string after the split.
https://www.tutorialspoint.com/python/string_split.htm
I'm sure this is covered in plenty of places, but I don't know the exact name of the action I'm trying to do so I can't really look it up. I've been reading an official Python book for 30 minutes trying to find out how to do this.
Problem: I need to put a string in a certain length "field".
For example, if the name field was 15 characters long, and my name was John, I would get "John" followed by 11 spaces to create the 15 character field.
I need this to work for any string put in for the variable "name".
I know it will likely be some form of formatting, but I can't find the exact way to do this. Help would be appreciated.
This is super simple with format:
>>> a = "John"
>>> "{:<15}".format(a)
'John '
You can use the ljust method on strings.
>>> name = 'John'
>>> name.ljust(15)
'John '
Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:
>>> name.ljust(15)[:15]
If you have python version 3.6 or higher you can use f strings
>>> string = "John"
>>> f"{string:<15}"
'John '
Or if you'd like it to the left
>>> f"{string:>15}"
' John'
Centered
>>> f"{string:^15}"
' John '
For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax
You can use rjust and ljust functions to add specific characters before or after a string to reach a specific length.
The first parameter those methods is the total character number after transforming the string.
Right justified (add to the left)
numStr = '69'
numStr = numStr.rjust(5, '*')
The result is ***69
Left justified (add to the right)
And for the left:
numStr = '69'
numStr = numStr.ljust(3, '#')
The result will be 69#
Fill with Leading Zeros
Also to add zeros you can simply use:
numstr.zfill(8)
Which gives you 00000069 as the result.
string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces
This will add the number of spaces needed, provided the field has length >= the length of the name provided
name = "John" // your variable
result = (name+" ")[:15] # this adds 15 spaces to the "name"
# but cuts it at 15 characters
I know this is a bit of an old question, but I've ended up making my own little class for it.
Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:
2021-03-02 update: Improved a bit - when working through a large codebase, you know whether the line you are writing is one you care about or not, but you don't know what was previously written to the console and whether you want to retain it.
This update takes care of that, a class variable you update when writing to the console keeps track of whether the line you are currently writing is one you want to keep, or allow overwriting later on.
class consolePrinter():
'''
Class to write to the console
Objective is to make it easy to write to console, with user able to
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------
#Class variables
stringLen = 0
overwriteLine = False
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteThisLine=False):
import sys
#Get length of stringIn and update stringLen if needed
if len(stringIn) > consolePrinter.stringLen:
consolePrinter.stringLen = len(stringIn)+1
ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
prevOverwriteLine = consolePrinter.overwriteLine
if prevOverwriteLine:
#Previous line entry can be overwritten, so do so
sys.stdout.write("\r" + ctrlString.format(stringIn))
else:
#Previous line entry cannot be overwritten, take a new line
sys.stdout.write("\n" + stringIn)
sys.stdout.flush()
#Update the class variable for prevOverwriteLine
consolePrinter.overwriteLine = overwriteThisLine
return
Which then is called via:
consolePrinter.writeline("text here", True)
If you want this line to be overwriteable
consolePrinter.writeline("text here",False)
if you don't.
Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.
I generally recommend the f-string/format version, but sometimes you have a tuple, need, or want to use printf-style instead. I did this time and decided to use this:
>>> res = (1280, 720)
>>> '%04sx%04s' % res
'1280x 720'
Thought it was a touch more readable than the format version:
>>> f'{res[0]:>4}x{res[1]:>4}'
First check to see if the string's length needs to be shortened, then add spaces until it is as long as the field length.
fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
rand += " "
Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.
def format_string(str, min_length):
while len(str) < min_length:
str += " "
return str