Reputation: 489
Can a string method, such as .rjust(), be saved in a variable and applied to a string?
Looked here but could not find a solution.
For example, instead of stating rjust(4, '-')
twice, can it be coded once in a variable and then passed to the two strings?
# Instead of this
print("a".rjust(4, '-'),
"xyz".rjust(4, '-'),
sep="\n")
# Something like this?
my_fmt = rjust(4, '-')
print("a".my_fmt,
"xyz".my_fmt,
sep="\n")
Both result in:
---a
-xyz
Upvotes: 2
Views: 186
Reputation: 5479
Why not just define a function like this:
def my_fmt(a_string):
return a_string.rjust(4, '-')
print(my_fmt("a"),my_fmt("xyz"), sep="\n")
#---a
#-xyz
Upvotes: 5
Reputation: 258
A similar result to what you are looking for would be the following
def my_fmt(my_str):
return my_str.rjust(4, '-')
print(my_fmt("a"),
my_fmt("xyz"),
sep="\n")
Rather than applying the "variable" to the string, it passes the string to a function that performs the desired operation.
Upvotes: 2