-1

suppose I have:

values = ['a', 1, 2, 3.462874271095e-13, 'c']

I would like to generate the following format string:

"My values are: %s, %d, %d, %f, %s" 

NOTE: Assume you don't know the type of the variables in the list, they can appear in any order. You are trying to determine whether to use %d, %f or %s. You can only have numbers and strings in the list. If you encounter a number with decimal places you don't want to print in scientific notation.

Denis
  • 11,796
  • 16
  • 88
  • 150
  • What have you tried so far? Where did you get stuck? – C.Nivs Jun 05 '19 at 14:08
  • PD - https://stackoverflow.com/questions/402504/how-to-determine-a-python-variables-type ? – splash58 Jun 05 '19 at 14:09
  • @C.Nivs I am able to determine the types using: `for itm in values: print(type(itm))` but I don't know how to replace using the newly formed array of types – Denis Jun 05 '19 at 14:13
  • Use [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance). for example: `"My values are: " + ", ".join(["%d" if isinstance(x, int) else "%f" if isinstance(x, float) else "%s" for x in values])` – pault Jun 05 '19 at 14:13
  • Do you want to generate the format string only, or do you want to *print* them (or include them in the string)? – CristiFati Jun 05 '19 at 14:15
  • @CristiFati I would like to generate a format string – Denis Jun 05 '19 at 14:15
  • Ah, OK, then it's a bit more complex, I thought you wanted to print them (`("My values are:" + " {:}," * (len(values) - 1) + " {:}").format(*values)`). – CristiFati Jun 05 '19 at 14:16

2 Answers2

4
formats = {
    int: "%d",
    float: "%f",
    str: "%s",
}

values = ['a', 1, 2, 3.462874271095e-13, 'c']
generated = "My values are: " + ", ".join(formats[type(v)] for v in values)
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
1

We need to map each possible type of value to its corresponding format wildcard. After that it's a simple matter of producing the string in the expected format:

wildcards = {
    str:   '%s',
    int:   '%d',
    float: '%f',
}

values = ['a', 1, 2, 3.462874271095e-13, 'c']
equiv  = (wildcards[type(x)] for x in values)

'My values are: ' + ', '.join(equiv)
=> 'My values are: %s, %d, %d, %f, %s'
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • easier to read so I guess I'm going to pick this one as both these solutions are the same – Denis Jun 05 '19 at 19:12