slices to the rescue :)

def left(s, amount):
    return s[:amount]

def right(s, amount):
    return s[-amount:]

def mid(s, offset, amount):
    return s[offset:offset+amount]
Answer from Andy W on Stack Overflow
🌐
InterviewQs
interviewqs.com β€Ί ddi-code-snippets β€Ί substring-python
Slice a string in python (right, left, mid equivalents) - InterviewQs
A step-by-step Python code example that shows how to slice a string (right, left, mid equivalents). Provided by InterviewQs, a mailing list for coding and data interview problems.
🌐
W3Schools
w3schools.com β€Ί python β€Ί python_ref_string.asp
Python String Methods
Python has a set of built-in methods that you can use on strings.
🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί string.html
string β€” Common string operations
Source code: Lib/string/__init__.py String constants: The constants defined in this module are: Custom string formatting: The built-in string class provides the ability to do complex variable subst...
🌐
Vultr Docs
docs.vultr.com β€Ί python β€Ί standard-library β€Ί str β€Ί rjust
Python str rjust() - Right-Justify String | Vultr Docs
December 31, 2024 - Specify a column width that is at least as wide as the longest string. Right-justify each string in the list using rjust().
🌐
Stanford CS
cs.stanford.edu β€Ί people β€Ί nick β€Ί py β€Ί python-string.html
Python Strings
Negative numbers also work within [ ] and slices: -1 is the last char in the string, and -2 is the next to last char, and so on. So for example with s = 'Python', s[-1] is 'n' and s[-2] is 'o'. This is convenient when you want to refer chars near the end of the string, and it works in slices too.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί python-right-and-left-shift-characters-in-string
Python - Right and Left Shift characters in String - GeeksforGeeks
July 12, 2025 - Positive values for rotate perform right shifts, while negative values perform left shifts. ... The result is obtained by converting the rotated deque back into a string.
Top answer
1 of 1
8

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?

🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί right align a string up to 20 characters and fill the rest of the space with *
r/learnpython on Reddit: Right align a string up to 20 characters and fill the rest of the space with *
January 27, 2025 -

This one is a bit hard to explain so I will just show the output for it. In this example the word is python, since python only has a length 6 characters, the rest of the space is filled with "*" to make the total number of characters 20 characters. To be honest I'm not even sure where start on this. Any help is appreciated.

Please type in a string: python
**************python
🌐
Tutorialspoint
tutorialspoint.com β€Ί python β€Ί string_rfind.htm
Python String rfind() Method
The following example shows the usage of Python String rfind() method. Here, we create a string, say "This is a string", and pass a substring of this string, say "is", as an argument to the method.
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί library β€Ί re.html
re β€” Regular expression operations
May 25, 2026 - A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right.
🌐
Google
developers.google.com β€Ί google for education β€Ί python β€Ί python strings
Python Strings | Python Education | Google for Developers
Python also has an older printf()-like facility to put together a string. The % operator takes a printf-type format string on the left (%d int, %s string, %f/%g floating point), and the matching values in a tuple on the right (a tuple is made of values separated by commas, typically grouped ...
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί library β€Ί stdtypes.html
Built-in Types β€” Python 3.14.6 documentation
Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space).
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί reference β€Ί expressions.html
6. Expressions β€” Python 3.14.6 documentation
The power operator ** binds less tightly than an arithmetic or bitwise unary operator on its right, that is, 2**-1 is 0.5. ... The % operator is also used for string formatting; the same precedence applies.
🌐
Real Python
realpython.com β€Ί python-strings
Strings and Character Data in Python – Real Python
December 22, 2024 - When you add a backslash before you press Enter, Python ignores the newline and interprets the whole construct as a single physical line. Sometimes, you need to include a literal backslash character in a string. If that backslash doesn’t precede a character with a special meaning, then you can insert it right ...
🌐
ListenData
listendata.com β€Ί home β€Ί python
String Functions in Python with Examples
The table below shows many common string functions in Python along with their descriptions and their equivalent functions in MS Excel. If you are intermediate MS Excel users, you must have used LEFT, RIGHT and MID Functions.
🌐
freeCodeCamp
freecodecamp.org β€Ί news β€Ί how-to-substring-a-string-in-python
How to Substring a String in Python
January 3, 2020 - Python offers many ways to substring a string. This is often called "slicing". Here is the syntax: string[start:end:step] Where, start: The starting index of the substring. The character at this index is included in the substring. If start is not in...
🌐
Sentry
sentry.io β€Ί sentry answers β€Ί python β€Ί extract a substring from a string in python
Extract a substring from a string in Python
2 weeks ago - Extract substrings from Python strings using slice notation with [start:end] indexes, or use re.search() with regex patterns for matching specific formats
🌐
Dot Net Perls
dotnetperls.com β€Ί right-python
Python - String Right Part - Dot Net Perls
December 13, 2021 - With a special method, we can get just the right part. But often using slice syntax directly is a better choice as it involves less code. Consider the string "soft orange cat." The last 3 characters are "cat," and so the result of right() with an argument of 3 should be "cat."
🌐
freeCodeCamp
freecodecamp.org β€Ί news β€Ί python-strip-how-to-trim-a-string-or-line
Python strip() – How to Trim a String or Line
January 12, 2022 - The following variable greeting has the string "Hello" stored in it. The string has space both to the right and left of it.