Demetri Pananos
Demetri Pananos

Reputation: 7404

How can I format a string with a string

Suppose I have a list of data

data= ['Mom','Dad',1,'Dog','World']

I want to format another string with these strings, but I want the formatting to be so that if the element in data is a string then it should be surrounded by quotes. I could use flow control, but would rather just use string formatting instead.

For instance, the desired output would be something like

You are my 'Mom'
You are my 'Dad'
You are my 1 #Notice that the 1 is an int and is not surrounded by quotes
You are my 'Dog'
You are my 'World'

Is there a way to format that?

Upvotes: 1

Views: 49

Answers (3)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160377

An alternate approach just to make up for my previous misinterpretation of the question (really is just a variation of @mgilsons approach):

fmt = "You are my {!r}"
print(*map(fmt.format, data), sep='\n')

which prints out the wanted result.

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191681

Though more verbose, a simple if statement should work

data= ['Mom','Dad',1,'Dog','World']

for d in data:
    print("You are my {}".format("'{}'".format(d) if isinstance(d, str) else d))

Output

You are my 'Mom'
You are my 'Dad'
You are my 1
You are my 'Dog'
You are my 'World'

Upvotes: 0

mgilson
mgilson

Reputation: 309821

You can use the !r format conversion specifier:

>>> data= ['Mom','Dad',1,'Dog','World']
>>> for item in data:
...     print('you are my {!r}'.format(item))
... 
you are my 'Mom'
you are my 'Dad'
you are my 1
you are my 'Dog'
you are my 'World'

This formats using __repr__ rather than __str__ (which is the default). Since str.__repr__ adds the quotes, it works out how you expect.

Upvotes: 3

Related Questions