0

I am trying to write a function which takes 6 inputs, a first and last name, two alignment characters and two lengths for alignment. The function is supposed to display the names using the alignment variables like so:

|First name  | Last name|
|John        |     Smith|

I understand how to do text alignment by directly inputting the desired values with f strings or string formatting e.g

{first_name:<12} 

but how do I substitute the :<12 with variables? I keep getting f string syntax errors. Her is what I am trying:

def display_name(first_name, last_name, align1, length1, align2, length2):

    if align1 == "L":
        align1 = "<"

    elif align1 == "R":
        align1 = ">"

    elif align1 == "C":
        align1 = "^"

    if align2 == "L":
        align2 = "<"

    elif align2 == "R":
        align2 = ">"

    elif align2 == "C":
        align2 = "^"

print(f"{|First name:{align1}.{length1}}|{Last name:{align2}.{length2}}|")
print(f"{|first_name:{align1}.{length1}}|{last_name:{align2}.{length2}}|")
1

2 Answers 2

1

You're very close. You should not include the | in your f-string specifier. Simply swap your | and {} and your code runs without errors.

print(f"|{first_name:{align1}.{length1}}|{last_name:{align2}.{length2}}|")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That alteration fixes the syntax error but i'm still not getting the desired output, which is to have the function arguments stand in for the alignment parameters. For instance if I make the print statements print(f"|First name:{align1}.{length1}}|{Last name:{align2}.{length2}|") print(f"|{first_name:{align1}.{length1}}|{last_name:{align2}.{length2}}|") and call the function display_name("John", "Smith", "L", 12, "R", 10) I get |First name:<.12|Last name:>.10| |John|Smith|
0

I think the answer is satisfactorily given here: Format in python by variable length

For convenience, here is a minimal example that solves the core of your issue. I haven't though of a way to make it work with f-formatting, but the ''.format() syntax works well here.

stuff='bananas'
('{:<'+str(12)+'}').format(stuff)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.