How to print a single backslash in python in a string? [duplicate]

2024/10/5 15:18:32

In python (3x version)

'\' # this is error no doubt
'\\' # this prints two backslashes ,i.e., '\\'
r'\' # this also gives error
'anytext \ anytext' # gives 'anytext \\ anytext'

r and R tried both but didn't work tried to escape the escape character \ ,i.e., '\\' but didn't work enter image description here

Answer

In IDLE (Python's Integrated Development and Learning Environment), expression values have their representation echoed to stdout.

As https://docs.python.org/3/library/idle.html explains:

The repr function is used for interactive echo of expression values.It returns an altered version of the input string in which controlcodes, some BMP codepoints, and all non-BMP codepoints are replacedwith escape codes.

If you want to print a string, use the print() function. Otherwise you'll get its representation.

Consider the following code entered into IDLE:

>>> hitman_str = "Agent \ 47"
>>> print(hitman_str) # We see only one slash when using print
Agent \ 47
>>> hitman_str # This shows the representation, which shows two slashes
'Agent \\ 47'
>>> print(repr(hitman_str)) # Same as above
'Agent \\ 47'

There are multiple ways to get a string with only one slash:

single_slash1 = "\\"
>>> print(single_slash1)
\
>>> single_slash2 = "\ "[0]
>>> print(single_slash2)
\
>>> single_slash1 == single_slash2
True

Similarly, there are multiple ways to get a string with two consecutive slashes:

>>> two_slashes1 = "\\\\"
>>> print(two_slashes1)
\\
>>> print(repr(two_slashes1))
'\\\\'
>>> two_slashes1
'\\\\'
>>> len(two_slashes1)
2
>>> two_slashes2 = r"\\"
>>> print(two_slashes2)
\\
>>> print(repr(two_slashes2))
'\\\\'
>>> two_slashes2
'\\\\'
>>> len(two_slashes2)
2

We can confirm hitman_str only has one slash:

>>> hitman_str.count(single_slash1)
1

We can iterate through the string and print each character and its Unicode code point. As expected, this shows only one slash:

>>> for char in hitman_str:print(char, ord(char))A 65
g 103
e 101
n 110
t 11632
\ 9232
4 52
7 55

Raw strings are very handy, especially for Windows paths if you don't wanna use os.path or pathlib:

>>> filename = r"C:\Users\Lee Hong\Documents\New Letters\Impatient 1999-06-14.txt" # Works fine
>>> filename = "C:\Users\Lee Hong\Documents\New Letters\Impatient 1999-06-14.txt" # Error
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> raw_str = r"This \\\has \11 \\slashes \\and \no \line \break"
>>> print(raw_str)
This \\\has \11 \\slashes \\and \no \line \break
>>> raw_str.count(single_slash1)
11

For more information, including a list of escape sequences to watch out for, refer to https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

https://en.xdnf.cn/q/119964.html

Related Q&A

Return nested JSON item that has multiple instances

So i am able to return almost all data, except i am not able to capture something like this:"expand": "schema""issues": [{"expand": "<>","id…

What request should I make to get the followers list from a specific profile page

I am trying to get the followers list from this profile, I tried making a GET request using python requests to the API using this request URL but it didnt seem to work, I got a METHOD_NOT_ALLOWED error…

PlayerDB API Post Requests bring 404

I made a little script to get the UUIDs of people who joined my minecraft server, then run them through the PlayerDB API through a post request to: https://playerdb.co/api/player/minecraft/* where the …

How to make changes using Configparser in .ini file persistent

How to modify the .ini file? My ini file looks like this. And i want the format section ini to be changed like this[Space to be replaced with a tab followed by $] Format="[%TimeStamp%] $(%Thre…

How to structure template libraries in a Django project? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.Clo…

Not able to click button with Selenium (Python)

Im trying to click a button using Selenium, but everytime I get the message that it cant find the element. This happens even when I put a time.sleep() in front of it. time.sleep(5)#Click on downloaddow…

how to aproximate shapes height and width for image detection using opencv and python

i was following a tutorial about shapes detection using opencv ,numpy and python ,and it was this function i know the reason from it but i do not know how to modify it so i can use it as i want the to…

Using str.replace in a for loop

I am working on an assignment that is asking me to change the below code so that line 4 uses str.isalnum and lines 5-7 become uses only one line using str.replace.s = p55w-r@d result = for c in s:if(c…

extract all vertical slices from numpy array

I want to extract a complete slice from a 3D numpy array using ndeumerate or something similar. arr = np.random.rand(4, 3, 3)I want to extract all possible arr[:, x, y] where x, y range from 0 to 2

Output an OrderedDict to CSV

I read a CSV file and use the usaddress library to parse an address field. How do I write the resulting OrderedDicts to another CSV file?import usaddress import csvwith open(output.csv) as csvfile:re…