carebear
carebear

Reputation: 771

Single quotes as a part of an element of a Python list

I searched around the web but couldn't find an answer. How can someone add a single quote as part of an element of a list in python? For example,

foo = ['the']

simple enough. But what if I want something like this?

foo = [''the']

where the element is 'the, with the single quotation appended?

Upvotes: 0

Views: 2058

Answers (4)

Kowalski
Kowalski

Reputation: 76

Use another quotation mark, just like below:

foo = ["'the"]
foo = ['"the']
foo = ['''"the''']
foo = ["""'the"""]

or use '\'

Upvotes: 2

Christian Tapia
Christian Tapia

Reputation: 34166

There are two ways of representing strings in Python (to avoid this issue):

some_string = '...'          # single quotes
some_string = "..."          # double quotes

Therefore, you can use the second one:

foo = ["'the"]

You can also escape the ' character:

foo = ['\'the']

Upvotes: 2

user521945
user521945

Reputation:

Escape the single quote '\'' or surround the string in double quotes "'".

Upvotes: 0

shx2
shx2

Reputation: 64328

Either use double-quotes when defining the string containing a single-quote character, or use single-quotes, and \-escape the inner single-quote:

"'the"
'\'the'

both work.

(Your question has got nothing to do with lists, only the string in your list...)

Upvotes: 1

Related Questions