Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8957067
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T14:54:10+00:00 2026-06-15T14:54:10+00:00

I am making a class that relies heavily on regular expressions. Let’s say my

  • 0

I am making a class that relies heavily on regular expressions.

Let’s say my class looks like this:

class Example:
    def __init__(self, regex):
        self.regex = regex

    def __repr__(self):
        return 'Example({})'.format(repr(self.regex.pattern))

And let’s say I use it like this:

import re

example = Example(re.compile(r'\d+'))

If I do repr(example), I get 'Example('\\\\d+')', but I want 'Example(r'\\d+')'. Take into account the extra backslash where that upon printing, it appears correctly. I suppose I could implement it to return "r'{}'".format(regex.pattern), but that doesn’t sit well with me. In the unlikely event that the Python Software Foundation someday changes the manner for specifying raw string literals, my code won’t reflect that. That’s hypothetical, though. My main concern is whether or not this always works. I can’t think of an edge case off the top of my head, though. Is there a more formal way of doing this?

EDIT: Nothing seems to appear in the Format Specification Mini-Language, the printf-style String Formatting guide, or the string module.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T14:54:11+00:00Added an answer on June 15, 2026 at 2:54 pm

    The problem with rawstring representation is, that you cannot represent everything in a portable (i.e. without using control characters) manner. For example, if you had a linebreak in your string, you had to literally break the string to the next line, because it cannot be represented as rawstring.

    That said, the actual way to get rawstring representation is what you already gave:

    "r'{}'".format(regex.pattern)
    

    The definition of rawstrings is that there are no rules applied except that they end at the quotation character they start with and that you can escape said quotation character using a backslash. Thus, for example, you cannot store the equivalent of a string like "\" in raw string representation (r"\" yields SyntaxError and r"\\" yields "\\\\").

    If you really want to do this, you should use a wrapper like:

    def rawstr(s):
        """
        Return the raw string representation (using r'') literals of the string
        *s* if it is available. If any invalid characters are encountered (or a
        string which cannot be represented as a rawstr), the default repr() result
        is returned.
        """
        if any(0 <= ord(ch) < 32 for ch in s):
            return repr(s)
    
        if (len(s) - len(s.rstrip("\\"))) % 2 == 1:
            return repr(s)
    
        pattern = "r'{0}'"
        if '"' in s:
            if "'" in s:
                return repr(s)
        elif "'" in s:
            pattern = 'r"{0}"'
    
        return pattern.format(s)
    

    Tests:

    >>> test1 = "\\"
    >>> test2 = "foobar \n"
    >>> test3 = r"a \valid rawstring"
    >>> test4 = "foo \\\\\\"
    >>> test5 = r"foo \\"
    >>> test6 = r"'"
    >>> test7 = r'"'
    >>> print(rawstr(test1))
    '\\'
    >>> print(rawstr(test2))
    'foobar \n'
    >>> print(rawstr(test3))
    r'a \valid rawstring'
    >>> print(rawstr(test4))
    'foo \\\\\\'
    >>> print(rawstr(test5))
    r'foo \\'
    >>> print(rawstr(test6))
    r"'"
    >>> print(rawstr(test7))
    r'"'
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm making a class that initializes instances of certain classes. This class will be
I'm new to this whole thing, and am making a web app that relies
I am making a base class that has a virtual method called GetBaseAddresses(). It
I'm making a C++11 class that produces a huge amount of data. That data
I tried making a wrapper class that encapsulates an object, a string (for naming
I am making a class Customer that has the following data members and properties:
Im making a login/logout class that logs users in, sets cookies based on user's
Im making a program for class that manages a Hotel. I have a function
I am making a program for class that manages a Hotel. I am able
While making some final tests of a class-library that I'm writing for Windows Mobile

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.