Home
Python
String Right Part
Updated Dec 13, 2021
Dot Net Perls
String right. A Python string contains many characters. Often we want just the last several characters—the ending, rightmost part of the string.
Implementation notes. 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.
Required output. 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."
soft orange cat RIGHT 3: cat
An example. Here we introduce a "right" method. Pay close attention to the return value of right(). It uses slice syntax with a negative start, and no end.
Tip We do not specify an end—this means the slice continues to the end of the string.
And We use a negative start—this means we start from that many characters from the end of the string.
def right(value, count): # To get right part of string, use negative first index in slice. return value[-count:] # Test the method. source = "soft orange cat" print(right(source, 3)) print(right(source, 1)) # We can avoid the "right" method entirely. # ... We can also use len in the expression. print(source[-2:]) print(source[len(source) - 2:])
cat t at at
Some notes. If you are using strings in Python, learning the slice syntax is essential. We get "right" and "left" parts as slices.
Summary. There is no substring() or right() method in the Python language. With slice indexes (some of which can be omitted) we get string parts.
Substring
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 13, 2021 (edit link).
Home
Changes
© 2007-2025 Sam Allen