md2614
md2614

Reputation: 489

Python string methods in a variable

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

Answers (2)

pakpe
pakpe

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

minterm
minterm

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

Related Questions