Philomath
Philomath

Reputation: 27

Adding quotes to an output in python

I am trying print the final output in single quotes, but unable to figure out how to do so. Kinda new to python, so any guidance to get me on the right track would be helpful.

I have tried concatenating quotes with the variable in the print function but getting 'invalid syntax' errors

sample = []
while True:
    print ('Enter items into this list or blank + enter to stop')
    name=input()
    if name == '':
        break
    sample = sample + [name]
print(sample)

sample.insert(len(sample)-1, 'and')
print(sample)

print('Here is the final output:')
print(*sample, sep = ", ")  

The final output shows something like which is fine: A, B, C, and, D

However, the desired output is: 'A, B, C, and, D'

Upvotes: 0

Views: 63

Answers (2)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

How about joining the list to a string beforehand using join, and then using that string in print via string.format or f-string

print('Here is the final output:')
print(sample)
s = ', '.join(sample).strip()
print(f"'{s}'")

The output will be

['A', 'B', 'C', 'and', 'D']
Here is the final output:
'A, B, C, and, D'

f-string for python3.6

s = ', '.join(sample).strip()

print(f"'{s}'")

Upvotes: 1

Shubham
Shubham

Reputation: 646

escape the quotes like below

print('\'hello world\'')

Or use the double quotes

print("'hello world'")

Upvotes: 0

Related Questions