How to trim spaces between list elements in an f-string? [duplicate]

2024/10/11 6:32:28

I have a string I am formatting and printing lists using f-string and I need to eliminate the spaces between list elements (and also after the first item ending in ':'). Here is my code:

if len(probably) > 0 and len(might) > 0:  print(f'{name}:',f'Might({might})', f'Probably({probably})')elif len(probably) == 0 and len(might) > 0:  print(f'{name}:',f'Might({might})')elif len(probably) > 0 and len(might) == 0:print(f'{name}:',f'Probably({probably})')elif len(probably) == 0 and len(might) == 0:print(f'{name}:')

and here is what it looks like currently:

1: Might(4, 6, 7) Probably(11)
2: Might(5, 8, 10) Probably(9)
3: Might(4, 5, 6, 7, 8, 12)
4: Might(1, 3, 6, 11, 12)
5: Might(2, 3, 8, 10) Probably(9)
6: Might(1, 3, 4, 7, 11)
7: Might(1, 3, 6)
8: Might(2, 3, 5, 9, 10)
9: Might(8, 10) Probably(2, 5)
10: Might(2, 5, 8, 9)
11: Might(4, 6) Probably(1)
12: Might(3, 4)
13:

and here is what I need it to look like

    1:Might(4,6,7) Probably(11)2:Might(5,8,10) Probably(9)3:Might(4,5,6,7,8,12)4:Might(1,3,6,11,12)5:Might(2,3,8,10) Probably(9)6:Might(1,3,4,7,11)7:Might(1,3,6)8:Might(2,3,5,9,10)9:Might(8,10) Probably(2,5)10:Might(2,5,8,9)11:Might(4,6) Probably(1)12:Might(3,4)13:
Answer

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})')
elif not probably and might:  print(f'{name}:', f'Might({might})')
elif probably and not might:print(f'{name}:', f'Probably({probably})')
elif not probably and not 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})')
elif not probably and might:  print(f'    {name}:Might({might_str})')
elif probably and not might:print(f'    {name}:Probably({probably_str})')
elif not probably and not 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:
https://en.xdnf.cn/q/118356.html

Related Q&A

Keeping name and score together while sorting

so I need to sort some high scores into order and here is the code I already have:def sortscores():namelist = []scorelist = []hs = open("hst.txt", "r")hscounter = 0for line in hs:if…

How to put values of pandas dataframe into a for loop in python?

This is a part of a Python API Connection program Here is the DataFrame SampleRegion Sector Brand ID Start Date 7188 US 41 40000 2006-03-06 7189 US 41 40345 2017-11-06 …

Partition Array

Given an array nums of integers and an int k, partition the array (i.e move the elements in nums) such that: All elements < k are moved to the left. All elements >= k are moved to the right Retur…

Tensorflow model accuracy

My model which I have trained on a set of 29K images for 36 classes and validated on 7K images. The model has a training accuracy of 94.59% and validation accuracy of 95.72% It has been created for OCR…

python email.message_from_string() parse problems

My setup uses fetchmail to pull emails from Gmail, which are processed by procmail and passes it to a python script.When I use email.message_from_string(), the resulting object is not parsed as an emai…

Python: Function returning highest value in list without max()? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 7…

Given edges, how can find routes that consists of two edges in a vectorised way?

I have an array of towns and their neighbours. I want to get a set all the pairs of towns that have at least one route that consists of exactly two different edges. Is there a vectorized way to do this…

Usefulness of one-line statements in Python [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

Pack data into binary string in Python [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Parsing Complex Mathematical Functions in Python

Is there a way in Python to parse a mathematical expression in Python that describes a 3D graph? Using other math modules or not. I couldnt seem to find a way for it to handle two inputs.An example of…