python split a string with special charcter [duplicate] - python

This question already has answers here:
How can I put an actual backslash in a string literal (not use it for an escape sequence)?
(4 answers)
Closed 1 year ago.
I need to split a string that I receive like that :
my_string = "\data\details\350.23.43.txt"
when I use my_string.replace ("\\", "/")
it returns : /data/detailsè.23.43.txt
It's considering the \350 in my string as a special character 'è'

Edit after your comment:
Try
my_string = r"\data\details\350.23.43.txt"
That happens because \ooo is interpreted as a character with octal value as described in the docs.
I guess the only way is to escape the \ as in:
my_string = "\data\details\\350.23.43.txt"
Then you can do stuff like:
my_string.split("\\")
Where do you get the string from? Is there a way to influence that?
And this looks like a path. It would be better to use
os.path.join("data", "details", "350.23.43.txt")
to create paths independently of the operating system.

\ in string literals are treated as escaping chars. That is why s1 = "line\nsecond line" creates a string with two lines. That is also why you use "\\" in my_string.replace ("\\", "/").
So to fix your problem, if you're using a string literal my string = "\data\details\350.23.43.txt" you should instead use "\\data\\details\\350.23.43.txt" to make sure your \ are properly escaped. Alternatively, you can use a raw string my string = r"\data\details\350.23.43.txt" by prepending r to the quote. That way nothing gets escaped (so r"\n" would be a 2 char string with \ and n instead of just a single new line char)

Related

How to avoid double backslashes in string literals being replaced with single backslash? [duplicate]

This question already has answers here:
How to write string literals in Python without having to escape them?
(6 answers)
Closed 7 months ago.
Python string replaces double backslash with a single backslash? How avoid replace? I need to keep \\n as it is.
Code:
if __name__ == "__main__":
str1 = '{"en":"M L\\n\\nL\\n\\nS","fr":""}'
print(str1)
print("{}".format(str1))
Output:
{"en":"M L\n\nL\n\nS","fr":""}
{"en":"M L\n\nL\n\nS","fr":""}
Expected output:
{"en":"M L\\n\\nL\\n\\nS","fr":""}
Use raw strings by inputting an r before the string:
r"M L\\n\\nL\\n\\nS"
This will ignore any and all escape characters.
Read more here: Raw Strings in Python
If you want to tell python to not convert \\ to \ you can specify your string as raw string. This will auto escape \ so they will be seen as they are. A raw string is a string that no characters can be escaped in it. You can do this by putting a r char before the string starts:
r"M L\\n\\nL\\n\\nS"
>>> "M L\\\\n\\\\nL\\\\n\\\\nS"
So you can see that python automatically escaped all the \ characters so when you use this string it will interpret as "M L\\n\\nL\\n\\nS".
If you have a multi line string you can do this the same way:
a = r"""abcdefg\n\t\a
dygkcy\d\wscd"""
note: There is no difference for ' and ".

how to replace '\' with '/' in python string [duplicate]

This question already has answers here:
python replace backslashes to slashes
(3 answers)
Closed 3 years ago.
I need to replace a python string that contains a number of '\':
String = 'A\BBC\CCB\:ABC'
goal = 'A/BBC/CCB/:ABC'
num = String.count('\')
String.replace('\','/')
But I keep getting error message:
SyntaxError: EOL while scanning string literal
The \ character in python has special uses. Eg. "\n" (newLine Character). In order to replace it in a string, you need to use one of the following:
String.replace('\\','/')
String.replace(r'\','/')
The "\" will look for the "\" character.
The r'\' will look for the raw interpretation of the string '\'
In your case you can do it like this:
string.replace('\\', '/', num)
Use '\', consider this situation:
print( "He said: \"Something about her.\"" );

Python: Trailing backslash in raw strings [duplicate]

This question already has answers here:
Why can't Python's raw string literals end with a single backslash?
(13 answers)
Closed 7 months ago.
The current Python grammar doesn't allow one to output a trailing \ in a raw string:
>>> print(r'a\b\c\')
SyntaxError: EOL while scanning string literal
On the contrary, you can write Bash like this:
echo 'a\b\c\'
I understand what the doc is saying. I wouldn't feel strange if an expression '\' fails because the backslash is escaping the quote. What I'm questioning is r'\': Aren't raw strings meant to be raw (which means backslashes in the string are taken literally)?
Do we have to write r'a\b\c' + '\\' or 'a\\b\\c\\' to make a string literal a\b\c\ in Python? I couldn't see how this is Pythonic.
From the documentation,
Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.
The limitation is due to the fact that you need someway to include a ' inside a raw string. Otherwise there is no way to put bob said "I'm not hungry" in a string.
So you end up in weird situation where you need an escape character for this case. So in raw strings you escape a ' with a \ and yes the \ stays in the string.
So r'bob said "I\'m not hungry"' it is!!
When you write print(r'\'), Python understand \' in that statement as a character. Because of that python raised syntax error because the there is a incomplete string inside print function.
For an example if you need to print i am "free" man , you should write
print("i am \"free\" man")

Can '\' be in a Python string? [duplicate]

This question already has answers here:
How can I put an actual backslash in a string literal (not use it for an escape sequence)?
(4 answers)
Closed 8 years ago.
I program in Python in PyCharm and whenever I write '\' as a string it says that the following statements do nothing. For example:
Is there a way to fix this and make it work?
Thanks.
You need to double the backslash:
'/-\\'
as a single backslash has special meaning in a Python string as the start of an escape sequence. A double \\ results in the string containing a single backslash:
>>> print '/-\\'
/-\
If the backslash is not the last character in the string, you could use a r'' raw string as well:
>>> print r'\-/'
\-/
You need to scape them to be in the string, for example:
>>>s='\\'
>>>print s
\
You can also use the r (raw string) modifier in front of the string to include them easily but they can't end with an odd number of backslash. You can read more about string literals on the docs.

python replace single backslash with double backslash [duplicate]

This question already has answers here:
How can I put an actual backslash in a string literal (not use it for an escape sequence)?
(4 answers)
Closed 7 months ago.
In python, I am trying to replace a single backslash ("\") with a double backslash("\"). I have the following code:
directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\")
However, this gives an error message saying it doesn't like the double backslash. Can anyone help?
No need to use str.replace or string.replace here, just convert that string to a raw string:
>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
Below is the repr version of the above string, that's why you're seeing \\ here.
But, in fact the actual string contains just '\' not \\.
>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'
>>> s = r"f\o"
>>> s #repr representation
'f\\o'
>>> len(s) #length is 3, as there's only one `'\'`
3
But when you're going to print this string you'll not get '\\' in the output.
>>> print strs
C:\Users\Josh\Desktop\20130216
If you want the string to show '\\' during print then use str.replace:
>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216
repr version will now show \\\\:
>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
Let me make it simple and clear. Lets use the re module in python to escape the special characters.
Python script :
import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)
Output :
C:\Users\Josh\Desktop
C:\\Users\\Josh\\Desktop
Explanation :
Now observe that re.escape function on escaping the special chars in the given string we able to add an other backslash before each backslash, and finally the output results in a double backslash, the desired output.
Hope this helps you.
Use escape characters: "full\\path\\here", "\\" and "\\\\"
In python \ (backslash) is used as an escape character. What this means that in places where you wish to insert a special character (such as newline), you would use the backslash and another character (\n for newline)
With your example string you would notice that when you put "C:\Users\Josh\Desktop\20130216" in the repl you will get "C:\\Users\\Josh\\Desktop\x8130216". This is because \2 has a special meaning in a python string. If you wish to specify \ then you need to put two \\ in your string.
"C:\\Users\\Josh\\Desktop\\28130216"
The other option is to notify python that your entire string must NOT use \ as an escape character by pre-pending the string with r
r"C:\Users\Josh\Desktop\20130216"
This is a "raw" string, and very useful in situations where you need to use lots of backslashes such as with regular expression strings.
In case you still wish to replace that single \ with \\ you would then use:
directory = string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\\\")
Notice that I am not using r' in the last two strings above. This is because, when you use the r' form of strings you cannot end that string with a single \
Why can't Python's raw string literals end with a single backslash?
https://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-are-escape-characters/
Maybe a syntax error in your case,
you may change the line to:
directory = str(r"C:\Users\Josh\Desktop\20130216").replace('\\','\\\\')
which give you the right following output:
C:\\Users\\Josh\\Desktop\\20130216
The backslash indicates a special escape character. Therefore, directory = path_to_directory.replace("\", "\\") would cause Python to think that the first argument to replace didn't end until the starting quotation of the second argument since it understood the ending quotation as an escape character.
directory=path_to_directory.replace("\\","\\\\")
Given the source string, manipulation with os.path might make more sense, but here's a string solution;
>>> s=r"C:\Users\Josh\Desktop\\20130216"
>>> '\\\\'.join(filter(bool, s.split('\\')))
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
Note that split treats the \\ in the source string as a delimited empty string. Using filter gets rid of those empty strings so join won't double the already doubled backslashes. Unfortunately, if you have 3 or more, they get reduced to doubled backslashes, but I don't think that hurts you in a windows path expression.
You could use
os.path.abspath(path_with_backlash)
it returns the path with \
Use:
string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\")
Escape the \ character.

Categories

Resources