Python for-loop syntax - python

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 :)

Related

How can I ouput a string with qoutes with a 'for' loop printing the index and given string in Python?

I would like to print out a string containing double quotes after appending multiple items in a for loop. However, they currently disappear.
def print_five(word):
for i in range(1, 6):
print(f"{i}{word}", end=" ")
print_five("rock")
This is the output right now:
1rock 2rock 3rock 4rock 5rock
However..., this the desired output:
"1rock 2rock 3rock 4rock 5rock "
This should work. Use backslash to escape the characters.
def print_five(word):
five_word = f"1{word}"
for i in range(2, 6):
five_word = five_word + f" {i}{word}"
print(f"\"{five_word} \"")
A more elegant solution similar to the one that seems to have been deleted. Note that when working with strings that are supposed to contain double-quotes, it makes sense to work with f-strings using single quotes:
def print_five(word):
print(f'"{" ".join([f"{i}{word}" for i in list(range(1, 6))])} "')
print_five("rock")
# "1rock 2rock 3rock 4rock 5rock "

Having a string with two quotes around it?

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\"')

How to remove backslashes in strings in python

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(" ' ", '')

The difference between these 2 strings?

I have recently started to learn Python and I am hoping that you will be able to help me with a question that has been bothering me. I have been learning Python online with Learn Python The Hard Way. In Exercise 6, I came across a problem where I was using the %r string formatting operation and it was resulting in two different strings. When I printed one string, I got the string with the single quotes (' '). With another I was getting double quotes (" ").
Here is the code:
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print "I said: %r." % x
print "I also said: %r." % y
The result from the first print statement:
I said: 'There are 10 types of people.'.
The result from the second print statement:
I also said: "Those who know binary and those who don't.".
I want to know why one of the statements had a result with the single quotes (' ') and another with (" ").
]
P.S. I am using Python 2.7.
%r is getting the repr version of the string:
>>> x = 'here'
>>> print repr(x)
'here'
You see, single quotes are what are normally used. In the case of y, however, you have a single quote (apostrophe) inside the string. Well, the repr of an object is often defined so that evaluating it as code is equal to the original object. If Python were to use single quotes, that would result in an error:
>>> x = 'those who don't'
File "<stdin>", line 1
x = 'those who don't'
^
SyntaxError: invalid syntax
so it uses double quotes instead.
Notice this line -> do_not = "don't". There is a single quote in this string, that means that single quote has to be escaped; otherwise where would the interpreter know where a string began and ended? Python knows to use "" to represent this string literal.
If we remove the ', then we can expect a single quote surrounding the string:
do_not = "dont"
>>> I also said: 'Those who know binary and those who dont.'.
Single vs. double quotes in python.

Proper way to deal with string which looks like json object but it is wrapped with single quote

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...

Categories