+ 2

Need help with this code please 😊

im a noob and need some help with this code please help. if the input string is longer than 79 characters it should print as is. otherwise it should print the string with enough leading spaces that last letter is in coloumn 80 of display. I got all section covered except when I enter a long string it gives me an error. def right_justify(input_string): pass # TODO: Complete this function value = input("Enter a word to justify: ") right_justify(value) len(value) print((80-len(value))* ' '+value)

10th Jan 2017, 11:05 AM
Alan_M
Alan_M - avatar
8 Answers
+ 5
if len(value)>79: print(value) else: print((80-len(value))*' '+value)
10th Jan 2017, 12:28 PM
DFX
DFX - avatar
+ 2
word=input("enter a word: ") def right_jus(x): if len(x)>78: return(x) else: return((80-len(x))*" "+x) print(right_jus(word))
10th Jan 2017, 12:28 PM
ramzi
ramzi - avatar
+ 2
it's because if the len is higher than 79, you will get a negative integer in your code, and you can't * a string with it.
10th Jan 2017, 12:32 PM
DFX
DFX - avatar
+ 2
def right_justify(input_string): length=len(input_string) number_of_spaces=length-80 if(number_of_spaces<0): number_of_spaces=abs(number_of_spaces) return ( " "*number_of_spaces +input_string) else: return(input_string) input_string=input("Enter a word to justify:") input_string=right_justify(input_string) print(input_string)
10th Jan 2017, 12:39 PM
heduson satchi
heduson satchi - avatar
+ 1
For a string longer than 80 characters you get a negative number when you subtract the length from 80. So put an if else around the print statement with an extra print to simply print value if its long.
10th Jan 2017, 12:34 PM
David Carter
+ 1
thnx guys you helped me out a lot. I was thinking about the if else statement but wasn't 100% sure.
10th Jan 2017, 7:45 PM
Alan_M
Alan_M - avatar
+ 1
nevermind, I was very tired and I thought if a word contained 70 letters, len(word) would be equal to 69 ..
10th Jan 2017, 8:30 PM
ramzi
ramzi - avatar
0
ramzi can you explain how my code ends up in 81 characters
10th Jan 2017, 1:16 PM
heduson satchi
heduson satchi - avatar