简体   繁体   中英

How to print quotes around a variable user inputted. Python

info = []
file = input("Enter a file ")

try:
    infile = open(file, 'r')

except IOError:
    print("Error: file" ,file, "could not be opened.")

if user enters file as filetest.txt,
This is my code.. I would like it to print Error: file "filetest.txt" could not be opened. Thanks for the help.

This works:

print('Error: file "{}" could not be opened.'.format(file))

See a demonstration below:

>>> file = "filetest.txt"
>>> print('Error: file "{}" could not be opened.'.format(file))
Error: file "filetest.txt" could not be opened.
>>>

In Python, single quotes can enclose double quotes and vice-versa. Also, here is a reference on str.format .


Lastly, I wanted to add that open defaults to read mode. So, you can actually just do this:

infile = open(file)

However, some people like to explicitly put the 'r' , so that choice is up to you.

print("Error: file \"{}\" could not be opened.".format(file))

Be careful, however, that file is a built-in type in python. Per convention, your variable should be named file_

Escape the quotes with a backslash

myFile = "myfile.txt"
print("Error: file \"" + myFile + "\" could not be opened.")

Prints:

Error: file "myfile.txt" could not be opened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM