Hello! There is a Python script, everything works, but there is one disadvantage: there are a couple of places in the code where the user must insert the path to the file. and since \ must be escaped, then you have to write \\, for example C: \\ papka \\ file.txt which is inconvenient, I would like the user to just copy and paste C: \ papka \ file.txt How to achieve this? code like this:

perv = input ('Π£ΠΊΠ°ΠΆΠΈΡ‚Π΅ ΠΏΡƒΡ‚ΡŒ ΠΊ измСняСмому Ρ„Π°ΠΉΠ»Ρƒ, \ Π·Π°ΠΌΠ΅Π½ΠΈ Π½Π° \\\: ') vtor = input ('ΠšΡƒΠ΄Π° ΡΠΎΡ…Ρ€Π°Π½ΠΈΡ‚ΡŒ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½Π½Ρ‹ΠΉ Ρ„Π°ΠΉΠ», \ Π·Π°ΠΌΠ΅Π½ΠΈ Π½Π° \\\: ') inp = open (perv, 'r') out = open (vtor, 'w') 
  • For ideas, you can try another slash: C:/papka/file.txt - gil9red
  • Thank you all for the answers, r '' helped! - babyborn

2 answers 2

The slash is escaped only in the source code . Do not confuse a string constant in the code (the textual representation of the string) and the corresponding string (the object itself) in memory.

For example, "\t" in the source code creates a string with one character (tab). But, if you call input() (Python 3) and type "\t" , the result is already: '"\\t"' (four characters: two quotes + forward slash + t). To get a tab, just press the Tab key for input() .

 >>> len('\t') == 1 True >>> len('\\t') == 2 True >>> r'\t' == '\\t' 

The last example uses raw string literal. Both expressions create the same string (there is no r'' in memory, only regular strings / objects).

When entering / outputting a slash, you do not need to escape the screen unless you try to interpret the input as Python source code.

    You can use the r specifier for a string that means that the string is entered in the raw format (you do not need to escape anything). Equally well suited for both regular expressions and paths:

      r"D:\Project\2014\archdata\folder1.ini" 

    qualifier can be set in upper case

    The advantages of such a solution are that readability does not fall compared with shielding.