In this example, the \t is a tab and \n is the new line. Print(dir_path) Code language: Python ( python ) Now, if you escape the first backslash, you’ll have other issues: dir_path = 'c:\\user\tasks\new' Python treats \u in the path as a Unicode escape but couldn’t decode it. If you use this path as a regular string, Python will issue a number of errors: dir_path = 'c:\user\tasks\new' Code language: Python ( python )Įrror: Synta圎rror: (unicode error) 'unicodeescape' codec can 't decode bytes in position 2-3: truncated \uXXXX escape Code language: Python ( python ) For example: c:\user\tasks\new Code language: Python ( python ) Windows OS uses backslashes to separate paths. Or s = r'\\\' Code language: Python ( python )Įrror: Synta圎rror: EOL while scanning string literal Code language: Python ( python ) Use raw strings to handle file path on Windows ![]() Since the backslash ( \) escapes the single quote ( ') or double quotes ( "), a raw string cannot end with an odd number of backslashes.įor example: s = r'\' Code language: Python ( python )Įrror: Synta圎rror: EOL while scanning string literal Code language: Python ( python ) Print(len(s)) # 2 Code language: Python ( python ) However, in a raw string, Python counts the backslash ( \) as one character: s = r'\n' Print(len(s)) # 1 Code language: Python ( python ) In a regular string, Python counts an escape sequence as a single character: s = '\n' Print(s1 = s2) # True Code language: Python ( python ) ![]() Output: lang\tver\nPython\t3 Code language: Python ( python )Ī raw string is like its regular string with the backslash ( \) represented as double backslashes ( \\): s1 = r'lang\tver\nPython\t3' However, raw strings treat the backslash ( \) as a literal character. ![]() Python 3 Code language: Python ( python ) Print(s) Code language: Python ( python ) To represent special characters such as tabs and newlines, Python uses the backslash ( \) to signify the start of an escape sequence. Raw strings are useful when you deal with strings that have many backslashes, for example, regular expressions or directory paths on Windows. Unlike a regular string, a raw string treats the backslashes ( \) as literal characters. In Python, when you prefix a string with the letter r or R such as r'.' and R'.', that string becomes a raw string. Summary: in this tutorial, you will learn about Python raw strings and how to use them to handle strings that treat backslashes as literal characters.
0 Comments
Leave a Reply. |