2

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
2
  • 1
    You can use functools.partial, but a lambda is easier. Lookup "Python lambda". Commented Feb 4, 2021 at 2:09
  • @user202729 Are you sure you can use a partial? I just tried but couldn't make it work cause str.rjust()'s parameters are self, width, fillchar=' ', /. Normally where the first parameter is self, you'd supply the others as kwargs, but that's not allowed. Also, named lambdas are bad practice; use a def instead. Commented Feb 4, 2021 at 2:27

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I tried that but implemented it incorrectly. Simple indeed.
2

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.

2 Comments

Same as above. Accepted theirs since it was posted first.
I think I was 15 seconds beforehand :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.