Simon
Simon

Reputation: 1125

Convert input to a string in Python

I want to wrap the colour input in quotes within python:

def main():
    colour = input("please enter a colour")

So if I enter red into the input box it automatically makes it "red"

I'm not sure how to do this, would it be something along the lines of:

def main():
    colour = """ + input("please enter a colour") + """

Kind regards

Upvotes: 2

Views: 13451

Answers (1)

Gareth Latty
Gareth Latty

Reputation: 89017

The issue is that this doesn't pass syntactically, as Python thinks the second " is the end of the string (the syntax highlighting in your post shows how it's being interpreted). The nicest to read solution is to use single quotes for the string: '"'.

Alternatively, you can escape characters (if you wish to, for example, use both types of quote in a string) with a backslash: "\""

A nice way of doing this kind of insertion of a value, rather than many concatenations of strings, is to use str.format:

colour = '"{}"'.format(input("please enter a colour"))

This can do a lot of things, but here, we are simply using it to insert the value we pass in where we put {}. (Note that pre-2.7, you will need to give the number of the argument to insert e.g: {0} in this case. Past that version, if you don't give one, Python will just use the next value).

Do note that in Python 2.x, you will want raw_input() rather than input() as in 2.x, the latter evaluates the input as Python, which could lead to bad things. In 3.x, the behaviour was fixed so that input() behaves as raw_input() did in 2.x.

Upvotes: 5

Related Questions