Print raw string from variable? (not getting the answers)

后端 未结 11 912
后悔当初
后悔当初 2020-12-04 10:14

I\'m trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like \'

相关标签:
11条回答
  • 2020-12-04 11:04

    I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com. But when I print it in the interactive mode I get double slash - '\\w' as @Jimmynoarms said:

    The Solution for python 3x:

    print(r'%s' % your_variable_pattern_str)
    
    0 讨论(0)
  • 2020-12-04 11:07

    In general, to make a raw string out of a string variable, I use this:

    string = "C:\\Windows\Users\alexb"
    
    raw_string = r"{}".format(string)
    

    output:

    'C:\\\\Windows\\Users\\alexb'
    
    0 讨论(0)
  • 2020-12-04 11:08

    try this. Based on what type of output you want. sometime you may not need single quote around printed string.

    test = "qweqwe\n1212as\t121\\2asas"
    print(repr(test)) # output: 'qweqwe\n1212as\t121\\2asas'
    print( repr(test).strip("'"))  # output: qweqwe\n1212as\t121\\2asas
    
    0 讨论(0)
  • 2020-12-04 11:10

    I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.

    Two ways of solving it:

    1. Get the path you want using native python functions, e.g.:

      test = os.getcwd() # In case the path in question is your current directory
      print(repr(test))
      

      This makes it platform independent and it now works with .encode. If this is an option for you, it's the more elegant solution.

    2. If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:

      test = 'C:\\Windows\\Users\\alexb\\'
      print(repr(test))
      
    0 讨论(0)
  • 2020-12-04 11:11

    Get rid of the escape characters before storing or manipulating the raw string:

    You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:

    >>> mypath = os.getcwd().replace('\\','/')  
    >>> os.path.exists(mypath)  
    True  
    >>>   
    
    0 讨论(0)
提交回复
热议问题