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
md2614
  • 353
  • 2
  • 14
  • 1
    You can use `functools.partial`, but a lambda is easier. Lookup "Python lambda". – user202729 Feb 04 '21 at 02: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](https://stackoverflow.com/a/38381663/4518341); use a `def` instead. – wjandrea Feb 04 '21 at 02:27

2 Answers2

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
pakpe
  • 5,391
  • 2
  • 8
  • 23
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.

minterm
  • 259
  • 3
  • 13