Skip to content Skip to sidebar Skip to footer

How To Trim Spaces In An F-string?

I have a string I am formatting and printing using f-string and I need to eliminate some spaces. Here is my code: if len(probably) > 0 and len(might) > 0: print(f'{n

Solution 1:

An f-string is still just a string at the end of the day:

>>> x = "hello">>> print(f"    {x}    ".strip())
hello

However, it's not quite clear what you expect your output to look like, as the spacing seems inconsistent between the number and the Might on each line:

3: Might(4,5,6,7,8,12)
4:Might(1,3,6,11,12)

Why is there a space in one and not the other? To add: you can take advantage of the truthiness of your objects and simplify your if-statements:

if probably and might:  
    print(f'{name}:', f'Might({might})', f'Probably({probably})')
elifnot probably and might:  
    print(f'{name}:', f'Might({might})')
elif probably andnot might:
    print(f'{name}:', f'Probably({probably})')
elifnot probably andnot might:
    print(f'{name}:')

If you want to get wild with truthiness, you can get rid of the if-statements entirely:

print(f"{name}:", f"Might({might})"*bool(might), f"Probably({probably})"*bool(probably))

EDIT

Since you've added some context via a comment, here's what you can do:

# Get rid of spaces between numbers
might_str = ",".join(map(str, might))
prob_str = ",".join(map(str, probably))

if probably and might:  
    print(f'    {name}:Might({might_str}) Probably({probably_str})')
elifnot probably and might:  
    print(f'    {name}:Might({might_str})')
elif probably andnot might:
    print(f'    {name}:Probably({probably_str})')
elifnot probably andnot might:
    print(f'    {name}:')

Some output including the leading spaces that you have in your "expected output":

    1:Might(1,2,3,4,5) Probably(5,6,2,3,1)
    2:Probably(5,6,2,3,1)
    3:Might(1,2,3,4,5)
    4:

Post a Comment for "How To Trim Spaces In An F-string?"