1

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?

2
  • Do you know how to iterate the data? Do you know how to check what data type a value is? Commented Dec 19, 2016 at 19:00
  • @takendarkk yes and yes, but flow control is not what I want to do. I am curious if I can accomplish it with formatting Commented Dec 19, 2016 at 19:03

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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'

1 Comment

I thought of this too, but wanted to avoid if-else statements because of the verbosity. Thanks
0

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.

2 Comments

In my question, I specify that if the data is a string, then it should have quotes.
Quite embarrassed :-)

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.