I am trying to replace a string here in Python.
This is my Input -
MyString = \\ServerA\DriveB\5.FolderC\A.TXT
I want my output to be like this
OutputString = //ServerA/DriveB/5.FolderC/A.TXT
I tried the replace method it didn't work. Is there a function that can convert it ? Kindly help me with this.
The Code tried,
MyString = '\\ServerA\DriveB\5.FolderC\A.TXT'
Output_String = MyString.replace('\', '//')
print(Output_String)
SyntaxError: EOL while scanning string literal
replace should work.
my_string = r'\\ServerA\DriveB\5.FolderC\A.TXT'
my_string = my_string.replace('\\', '/')
Two things that commonly go wrong:
If you're not assigning back to a variable.
If you're not escaping the \.
Also, note that I'm using a raw string (using an r prefix) to make sure characters aren't escaped in the original string.
Related
Is it possible to insert a backslash when a special character appears on string ?
Raw String:
echo "The string is: Ytds^&4"
Output expected:
echo "The string is: Ytds\^\&4"
Can I use python or shell.
You could use a manual chain of .replace(), which would be messy.
You could also just use a function like this:
str_ = "Y^541"
def change(string: str, characters):
for character in characters:
string = string.replace(character, "\\" + character)
return string
print(change(str_, "!##$%^&*()")) # output: Y\^541
The argument characters should be a string of all the characters which are considered as special, and it does a loop to replace each of those characters with a backslash.
In Python, the following will produce exactly the required output:
print('The string is: Ytds\^\&4')
This is because neither the caret nor the ampersand are escapable characters and therefore the backslash is interpreted literally giving this output:
The string is: Ytds\^\&4
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)
I'm trying to remove the apostrophe from a string in python.
Here is what I am trying to do:
source = 'weatherForecast/dataRAW/2004/grib/tmax/'
destination= 'weatherForecast/csv/2004/tmax'
for file in sftp.listdir(source):
filepath = source + str(file)
subprocess.call(['degrib', filepath, '-C', '-msg', '1', '-Csv', '-Unit', 'm', '-namePath', destination, '-nameStyle', '%e_%R.csv'])
filepath currently comes out as the path with wrapped around by apostrophes.
i.e.
`subprocess.call(['', 'weatherForecast/.../filename')]`
and I want to get the path without the apostrophes
i.e.
subprocess.call(['', weatherForecast/.../filename)]
I have tried source.strip(" ' ", ""), but it doesn't really do anything.
I have tried putting in print(filepath) or return(filepath) since these will remove the apostrophes but they gave me
syntax errors.
filepath = print(source + str(file))
^
SyntaxError: invalid syntax
I'm currently out of ideas. Any suggestions?
The strip method of a string object only removes matching values from the ends of a string, it stops searching for matches when it first encounters a non-required character.
To remove characters, replace them with the empty string.
s = s.replace("'", "")
The accepted answer to this question is actually wrong and can cause lots of trouble. strip method removes as leading/trailing characters. So you use it when you have character to remove from start and end.
If you use replace instead, you will change all characters in the string. Here is a quick example.
my_string = "'Hello rokman's iphone'"
my_string.replace("'", "")
The above code will return Hello rokamns iphone. As you can see you lost the quote before s. This is not someting you would need in your case. However, you only parse location without that character I believe. That's why it was ok for you to use at that time.
For the solution, you are doing just one thing wrong. When you call strip method you leave space before and after. The right way to use it should be like this.
my_string = "'Hello world'"
my_string.strip("'")
However this assumes that you got ', if you get " from the response you can change quotes like this.
my_string = '"Hello world"'
my_string.strip('"')
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.
How would I add the "\" char to a string?
For instance, if I have "testme" and I do
"testme"+"\"
I would get an error.
What is a "pythonic" approach for adding a "\" before each paren in a string?
For instance to go from "(hi)" to "\(hi\)"
My current approach is to iterate through each char and try to append a "\" which I feel isn't that "pythonic"
Backslashes are used for escaping various characters, so to include a literal backslash in your string you need to use "\\", for example:
>>> print "testme" + "\\"
testme\
So to add a backslash before each paren in a string you could use the following:
s = s.replace('(', '\\(').replace(')', '\\)')
Or with regular expressions:
import re
s = re.sub(r'([()])', r'\\\1', s)
Note that you can also use a raw string literal by adding a the letter r before the opening quote, this makes it so that backslash is interpreted literally and no escaping is done. So r'foo\bar' would be the same as 'foo\\bar'. So you could rewrite the first approach like the following:
s = s.replace('(', r'\(').replace(')', r'\)')
Note that even in raw string literals you can use a backslash to escape the quotation mark used for the string literal, so r'we\'re' is the same as 'we\'re' or "we're". This is why raw string literals don't work well when you want the final character to be a backslash, for example r'testme\' (this will be a syntax error because the string literal is never closed).
>>> import re
>>> strs = "(hi)"
>>> re.sub(r'([()])',r'\\\g<0>',strs)
'\\(hi\\)'
"\" is invalid because you're escaping the closing quote here, so python will raise EOF error.
So you must escape the \ first using another \:
>>> "\\"
'\\'
>>> "\"
File "<ipython-input-23-bdc6fd40f381>", line 1
"\"
^
SyntaxError: EOL while scanning string literal
>>>