How can I have a string like "'1'"? I have tried:
a = str(str(1))
but result still is '1'.
Use escape sequence:
print("\"\"1\"\"")
>> print("\"\"1\"\"")
""1""
BTW, this method is used by many people hence this is preferable :)
You can add those characters to your string using placeholders, doing so:
a = '"%s"'% a
You can use single quotes inside a double quoted string as mentioned above: "'1'" or '"1"' or you can escape quotes like '\'1\'' or "\"1\"". See for example Python Escape Characters.
Here is one way:
def single_quoted(s):
return "'" + s + "'"
def double_quoted(s):
return '"' + s + '"'
a = double_quoted(single_quoted(str(1)))
print(a)
It is very verbose so you can see what each individual part does, without inspecting your code carefully to find where each ' and " is. The output is
"'1'"
By the way, maybe you actually need this:
a = single_quoted(str(1))
print(a)
This outputs
'1'
If you want to use func call as you ask; try this solution:
str('\"1\"')
Related
I have this string s = "(0|\\+33)[1-9]( *[0-9]{2}){4}". And I want to delete just the duplicated just one ' \ ', like I want the rsult to look like (0|\+33)[1-9]( *[0-9]{2}){4}.
When I used this code, all the duplicated characters are removed:
result = "".join(dict.fromkeys(s)).
But in my case I want just to remove the duplicated ' \ '. Any help is highly appreciated
A solution using the re module:
import re
s = r"(0|\\+33)[1-9]( *[0-9]{2}){4}"
s = re.sub(r"\\(?=\\)", "", s)
print(s)
I look for all backslashes, that are followed by another backslash and replace it with an empty sign.
Output: (0|\+33)[1-9]( *[0-9]{2}){4}
The function you need is replace
s = "(0|\\+33)[1-9]( *[0-9]{2}){4}"
result = s.replace("\\","")
EDIT
I see now that you want to remove just one \ and not both.
In order to do this you have to modify the call to replace this way
result = s.replace("\","",1) # last argument is the number of occurrances to replace
or
result = s.replace("\\","\")
EDIT of the EDIT
Backslashes are special in Python.
I'm using Python 3.10.5. If I do
x = "ab\c"
y = "ab\\c"
print(len(x)==len(y))
I get a True.
That's because backslashes are used to escape special characters, and that makes the backslash a special character :)
I suggest you to try a little bit with replace until you get what you need.
Below is the string I'm operating on.
'exampleURL': ' '
'https://someurl.com'
I'm trying to clean it up using the code below. But for some reason, it doesn't work.
value_to_keep = (value_to_keep.rstrip('"').lstrip('"').rstrip("\n").lstrip("\n").rstrip("'").lstrip("'"))
I want the desired output to be
'exampleURL': 'https://someurl.com'
What is it that I'm missing here?
Answering my own question. I have solved the issue by improving the pattern.
rstrip("' '").lstrip("' '")
Instead of one single quote, I have added two with a space. Because, that's how it is in the string.
You can simply use the replace method and replace(" ", "")
foo = {
'exampleURL': '
https://someurl.com'.replace(" ", "")
}
print(foo['exampleURL'])
Output: https://someurl.com
As an output of Pytesseract, I get a string variable which contains backslashes. I would like to remove all of the back slashes.
'13, 0\\'70'
Unforturnately the replace function does not work as the string doesn't seem to be an actual string when the variable value is copied. Anybody knows how I can remove all the backslashes?
I replaced your outermost quotation marks with double-quotes, and then properly applied `replace:
>>> brut_mass = "13, 0\\'70"
>>> brut_mass.replace('\\', '')
"13, 0'70"
Does that solve your problem?
Fixed it with the code below.
brut_mass = repr(brut_mass).replace(" ' ", '')
or alternatively to avoid the double quotations
brut_mass = brut_mass.replace(" ' ", '')
for i in range(2, job_count+1):
job_count_array['//form[#id='SubAvailSelectForm']/font/table[2]/tbody/tr[%d]/td[1]/small' % i] = sel.get_text("//form[#id='SubAvailSelectForm']/font/table[2]/tbody/tr[%d]/td[1]/small" % i)
I am getting a syntax error with the value side of this dictionary entry. Let me know what looks wrong to you. The interpreter is pointing to the % i). Thanks!
Look at the syntax highlighting. You can’t just put a plain ol’ ' in your '-delimited string.
Escape them as \', or change your quotes to be consistent with the second string:
for i in range(2, job_count+1):
job_count_array["//form[#id='SubAvailSelectForm']/font/table[2]/tbody/tr[%d]/td[1]/small" % i] = sel.get_text("//form[#id='SubAvailSelectForm']/font/table[2]/tbody/tr[%d]/td[1]/small" % i)
Your problem is here:
job_count_array['//form[#id='SubAvailSelectForm']/font/table[2]/tbody/tr[%d]/td[1]/small' % i]...
do "//form..." instead of '//form...': double quotes instead of single. As in your string you have 'SubAvailSelectForm', which is quoted with single quotes. So either make your string double-quoted, or escape single quotes in your string: '\''
You have single quotes inside single quotes. The interpreter is confused :)
By definition the JSON string is wrapped with double quote.
In fact:
json.loads('{"v":1}') #works
json.loads("{'v':1}") #doesn't work
But how to deal with the second statements?
I'm looking for a solution different from eval or replace.
Thanks.
If you get a mailformed json why don't you just replace the double quotes with single quotes before
json.load
If you cannot fix the other side you will have to convert invalid JSON into valid JSON. I think the following treats escaped characters properly:
def fixEscapes(value):
# Replace \' by '
value = re.sub(r"[^\\]|\\.", lambda match: "'" if match.group(0) == "\\'" else match.group(0), value)
# Replace " by \"
value = re.sub(r"[^\\]|\\.", lambda match: '\\"' if match.group(0) == '"' else match.group(0), value)
return value
input = "{'vt\"e\\'st':1}"
input = re.sub(r"'(([^\\']|\\.)+)'", lambda match: '"%s"' % fixEscapes(match.group(1)), input)
print json.loads(input)
Not sure if I got your requirements right, but are you looking for something like this?
def fix_json(string_):
if string_[0] == string_[-1] == "'":
return '"' + string_[1:-1] +'"'
return string_
Example usage:
>>> fix_json("'{'key':'val\"'...cd'}'")
"{'key':'val"'...cd'}"
EDIT: it seems that the humour I tried to have in making the example above is not self-explanatory. So, here's another example:
>>> fix_json("'This string has - I'm sure - single quotes delimiters.'")
"This string has - I'm sure - single quotes delimiters."
This examples show how the "replacement" only happens at the extremities of the string, not within it.
you could also achieve the same with a regular expression, of course, but if you are just checking the starting and finishing char of a string, I find using regular string indexes more readable....
unfortunately you have to do this:
f = open('filename.json', 'rb')
json = eval(f.read())
done!
this works, but apparently people don't like the eval function. Let me know if you find a better approach. I used this on some twitter data...