How to remove forward slash (\) from a string in Python? - python-3.x

I am trying to remove all the backslashes from a string in my code, however when I tried the following:
a = 'dfdfd\dafdfd'
print(a)
a.replace('\',' ')
... I encountered the following error:
File "<stdin>", line 1
a.replace('\',' ')
Can someone explain why this is happening, and how do I fix it?

You need to use raw r'' string -
a.replace(r'\',' ')

You can this way(One more way to do):
a = 'dfdfd\dafdfd'
exclude = '\\'
s = ''.join(ch for ch in a if ch not in exclude)
print(s)

The backslash (\) character is an escape character. When you wrote
a.replace('\',' ')
... Python interpreted the \' as a ' inside the string, and therefore threw an error since the parser messed up. Therefore, you need to fix this by escaping the backslash character with another backslash, like so:
a.replace('\\',' ')

Related

removing the matched character in string

original_string ="helloworld"
characters_to_remove="world"
for character in characters_to_remove:
if original_string.find(character) == -1:
continue
else:
# remove matched character
original_string = original_string.replace(character,'',1)
print(original_string)
output:hello
(BUt get getting output is:helol) can any one resolve this issue
Your problem is obvious.
The 'l' in 'world' also appears in 'hello'. So what is happening is two things: your code is removing the first l in hello and then ignoring the l in world, because you are actually looping through 'w','o','r','l','d' just once.
A far better way to do this is to use a regex and python's great many string libraries, for example:
import re
re.sub('world', '', "helloworld")
Without the re module you can use find and replace functions to replace the partial string :
original_string ="helloworld"
characters_to_remove="world"
pos = original_string.find(characters_to_remove)
original_string = original_string.replace(original_string[pos:pos + len(characters_to_remove)],"")

How do I add the ' symbol to a string

I had someone help with a prior question to turn hexadecimal to string, but I want the string to output surrounded with '
so it returns 'I0KB' instead of just I0KB.
What I have:
with open('D:\new 4.txt', 'w') as f:
f.write('if not (GetItemTypeId(GetSoldItem())==$49304B42) then\n')
def hex_match_to_string(m):
return ''.join([chr(int(m.group(1)[i:i+2], 16)) for i in range(0, len(m.group(1)), 2)])
# ...
line = re.sub(r'\$((?:\w\w\w\w\w\w\w\w)+)', hex_match_to_string, line)
file_out.write(line)
output:
if not (GetItemTypeId(GetSoldItem())==I0KB) then
but I want it to output
if not (GetItemTypeId(GetSoldItem())=='I0KB') then
and using
def hex_match_to_string(m):
return ''.join(',[chr(int(m.group(1)[i:i+2], 16)) for i in range(0, len(m.group(1)), 2)],')
...gives me a syntax error even though I read that join(a,b,c) is the way to combine strings.
Thanks in advance for the help, and sorry I am clueless for what should be an easy task.
You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string.
You should not add the quotes to the argument passed to join, but wrap the result of the join with quotes:
return "'" + ''.join([chr(int(m.group(1)[i:i+2], 16)) for i in range(0, len(m.group(1)), 2)]) + "'"
I think it's important to distinguish between enclosing a string between, single, double, or triple quotation marks. See answers here regarding the most common use of the third (the so-called doc-strings).
While most of the time you can use " and ' interchangeably, you can use them together in order to escape the quotation:
>>> print("''")
''
>>> print('"')
"
You can also use the double quotes three times to escape any double quotes in between:
>>> print(""" " " "j""")
" " "j
But I'd suggest against the last option, because it doesn't always work as expected, for example, print(""""""") will throw an error. (And of course, you could always use the \ to escape any special character.)

\n in Python 3 confusion

I am pretty new at python. So, I get this
SyntaxError: unexpected character after line continuation character
after running this:
print (full_name.title()\nfull_name.upper()\nfull_name.lower())
Any idea why?
You must separate each string by a comma, and the use quotes around the strings:
print(full_name.title(), '\n', full_name.upper(), '\n', full_name.lower())
Alternatively, you could first concatenate the fragments, then print the resulting string:
string_to_print = full_name.title() + '\n' + full_name.upper() + '\n' + full_name.lower()
print(string_to_print)
There are more sophisticated approaches too (f-strings, format, __str__, etc.) that you may want to look up once you have mastered the basics.

Replace two backslashes with a single backslash

I want to replace a string with two backslashes with single backslashes. However replace doesn't seem to accept '\\' as the replacement string. Here's the interpreter output:
>>> import tempfile
>>> temp_folder = tempfile.gettempdir()
>>> temp_folder
'C:\\Users\\User\\AppData\\Local\\Temp'
>>> temp_folder.replace('\\\\', '\\')
'C:\\Users\\User\\AppData\\Local\\Temp'
BTW, I know that Windows paths need to contain either double backslashes or a single forward slashes. I want to replace them anyway for display purposes.
Your output doesn't have double backslashes. What you are looking at is the repr() value of the string and that displays with escaped backslashes. Assuming your temp_folder would have double backslashes, you should instead use:
print(temp_folder.replace('\\\\', '\\'))
and that will show you:
C:\Users\User\AppData\Local\Temp
which also drops the quotes.
But your temp_folder is unlikely to have double backslashes and this difference in display probably got you thinking that there are double backslashes in the return value from tempfile.gettempdir(). As #Jean-Francois indicated, there should not be (at least not on Windows). So you don't need to use the .replace(), just print:
print(temp_folder)
This works for me
text = input('insert text')
list = text.split('\\')
print(list)
text2 = ''
for items in list:
if items != '':
text += items + '\\'
print(text2)

Syntax error in removing bad character in groovy

Hello I have a string like a= " $ 2 187.00" . I tried removing all the white spaces and the bad characters like a.replaceAll("\\s","").replace("$","") . but i am getting error
Impossible to parse JSON response: SyntaxError: JSON.parse: bad escaped character how to remove the bad character in this expression so that the value becomes 2187.00.Kindly help me .Thanks in advance
def a = ' $ 2 187.00'
a.replaceAll(/\s/,"").replaceAll(/\$/,"")
// or simply
a.replaceAll(/[\s\$]/,"")
It should return 2187.00.
Note
that $ has special meaning in double quoted strings literals "" , called as GString.
In groovy, you can user regex literal, using that is better than using regex with multiple escape sequences in string.

Resources