Cheating
Both functions look like you've failed to do the assignment. The problem description talks about the len(...)
function, and how it behaves with strings. You are not using it to write the function. Ok, maybe it doesn't explicitly say you have to use it, but it seems implied! Instead, you've scoured the standard library and determined two different functions which do the work for you. I think the point of the question is re-inventing the wheel ... writing a function like .rjust(w)
yourself!
Which option is better?
Consider what the functions do:
With '{:>70}'.format(s)
, the format function has to scan the '{:>70}'
string for {}
, break it up into field and format codes, take arguments from the .format(...)
parameter and/or keyword list, and interpolate those into the string at the appropriate places, applying the required formatting. In short, it powerful, but computationally expensive.
If s
is not a string, the function will still work, implicitly formatting the result with str(s)
, which is one of the advantages of the additional power in this approach.
With s.rjust(70)
, it is taking a string and padding it on the left with (by default) spaces. Simple and fast.
If s
is not a string (or another class which defines .rjust()
), it will raise an exception.
So, ...
- the first is "better", in terms of the Robustness Principle in the sense that it works with more arguments.
- the second is "better" in terms of efficiency
Additional possibilities
You can cheat and write the function even shorter, using f-strings:
def right_justify(s: str) -> None:
"""
Print out the given argument right-justified to 70 characters,
followed by a newline.
Note: If the string is longer than 70 characters, it is printed
without modification.
"""
print(f'{s:>70}')
Well, it was shorter until I added argument type-hints, a return value type-hint, and a """docstring"""
... which are all "best practices".
But, the assignment goal is still not satisfied. Without these magical format functions or .rjust
methods, can you write a function which will accomplish the goal yourself?