Hey everyone,

Here's a question that should be pretty simple that I haven't found the answer to: if I'm using a function that takes some characters in quotes, what do I do if I want quotes to be some of those characters? I.e, if my code says

if c in '!,.?$%'

what would I do if I wanted to include an apostrophe along with !,.?$% for c?

Dani AI

Generated

Both quick ideas already posted by and are valid: you can change which quote character bounds the literal so the apostrophe does not need escaping, or you can escape it. For longer scripts or more robust checks there are a few other patterns that are often cleaner or faster.

If the goal is "is this a punctuation character?", use the standard library constant rather than hard‑coding a literal set. The string module exposes punctuation, which includes the ASCII apostrophe.

import string

if c in string.punctuation:
    # handle punctuation

Sometimes text contains a typographic right single quote (smart quote) rather than the ASCII apostrophe. Either normalize input or test for both characters explicitly:

if ord(c) == 39:
    # ASCII apostrophe

if c in ("'", "\u2019"):
    # ASCII or typographic apostrophe

If performance matters (checking many characters repeatedly), build a set for O(1) membership instead of repeated string scans. Also consider using regular expressions for pattern checks or unicodedata normalization when dealing with text from varied sources.

References: Python standard library string.punctuation documentation is useful for this use case: string — Common string operations.

Recommended Answers

All 4 Replies

Try ...
if c in "!,.?'$%"

Yes, what vegaseat suggested... either that or use an escape (a la \) before the text as in:

>>> t = '!,.?\'$%'
>>> print t
!,.?'$%
>>>

Same thing goes for double quotes within double-quoted string:

>>> t = "!,.?\"$%"
>>> print t
!,.?"$%
>>>

Using an escape character like jlm699 showed is the best general approach. You can even ecape the escape character like this ...
if c in "!,.?\'\"\\$%"

Cool, thanks, people.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.