I'm working on something in Python and I need to escape from %20, the space in a URL. For example:
"%20space%20in%20%d--" % ordnum
So I need to use %20 for a URL but then %d for a number. But I get this error:
TypeError: not enough arguments for format string
I know what the problem is I just don't know how to escape from a %20 and fix it.
One way would be to double the % characters:
"%%20space%%20in%%20%d--" % ordnum
but a probably better way is using urllib.quote_plus():
urllib.quote_plus(" space in %d--" % ordnum)
The %20 should look like %%20 when Python's formatter sees it. To Python, %% formats out to %.
>>> import urllib
>>> unquoted = urllib.unquote("%20space%20in%20%d--")
>>> ordnum = 15
>>> print unquoted % ordnum
space in 15--
I see three ways to solve this:
Escape the %.
"%%%20dogs" % 11
Use the new .format syntax.
"{}%20dogs".format(11)
Use the + sign instead of %20, as I think that's possible as well.
"%+dogs" % 11
Related
I am having trouble with the replace() method. I want to replace some part of a string, and the part which I want to replace consist of multiple escape characters. It looks like something like this;
['<div class=\"content\">rn
To remove it, I have a block of code;
garbage_text = "[\'<div class=\\\"content\\\">rn "
entry = entry.replace(garbage_text,"")
However, it does not work. Anything is removed from my complete string. Can anybody point out where exactly I am thinking wrong about it? Thanks in advance.
Addition:
The complete string looks like this;
"['<div class=\"content\">rn gitar calmak icin kullanilan minik plastik garip nesne.rn </div>']"
You could use the triple quote format for your replacement string so that you don't have to bother with escaping at all:
garbage_text = """['<div class="content">rn """
Perhaps your 'entry' is not formatted correctly?
With an extra variable 'text', the following worked in Python 3.6.7:
>>> garbage_text
'[\'<div class=\\\'content\'\\">rn '
>>> text
'[\'<div class=\\\'content\'\\">rn And then there were none'
>>> entry = text.replace(garbage_text, "")
>>> entry
'And then there were none'
for each_ID ,each_Title in zip(Id,Title):
url="http://www.zjjsggzy.gov.cn/%E6%96%B0%E6%B5%81%E7%A8%8B/%E6%8B%9B%E6%8A%95%E6%A0%87%E4%BF%A1%E6%81%AF/jyxx_1.html?iq=x&type=%E6%8B%9B%E6%A0%87%E5%85%AC%E5%91%8A&tpid=%s&tpTitle=%s"%(each_ID,each_Title)
“each_ID”and “each_Title” are from website unicode parameters, but why it cause a “float”error, %s is not a string?
You have loads of % formatters in your string. %E formats a float object. You have several of those in your string, including at the start:
"http://www.zjjsggzy.gov.cn/%E6
# ^^
You'd need to double up every single % used in a URL character escape:
"http://www.zjjsggzy.gov.cn/%%E6%%96%%B0%%E6%%B5%%81%%E7%%A8%%8B/..."
That'd be a lot of work, you'd be better off using a different string formatting style. Use str.format():
url = (
"http://www.zjjsggzy.gov.cn/"
"%E6%96%B0%E6%B5%81%E7%A8%8B/%E6%8B%9B%E6%8A%95%E6%A0%87%E4%BF%A1%E6%81%AF"
"/jyxx_1.html?iq=x&type=%E6%8B%9B%E6%A0%87%E5%85%AC%E5%91%8A&"
"tpid={}&tpTitle={}".format(
each_ID, each_Title)
)
I broke the string up into multiple chunks to make it easier to read; the {} brackets delineate the placeholders.
Try using the format method on string. The existing '%' chars conflicting with your %s placeholders :
for each_ID ,each_Title in zip(Id,Title):
url="http://www.zjjsggzy.gov.cn/%E6%96%B0%E6%B5%81%E7%A8%8B/%E6%8B%9B%E6%8A%95%E6%A0%87%E4%BF%A1%E6%81%AF/jyxx_1.html?iq=x&type=%E6%8B%9B%E6%A0%87%E5%85%AC%E5%91%8A&tpid={}&tpTitle={}".format(each_ID, each_Title)
I have a string like
This was really "e;awesome"e; isn't it?
And i need to convert the text to this format
This was really \"awesome\" isn't it?
I tried to use replace(""e;", "\"") but I got this one:
This was really "awesome" isn\'t it?
Which is not exactly what I am trying to get.
Any idea?
Try using replace(""e;", r'\"'). The r'...' with the "r" in front of the quotes means make it a "raw" string, so the backslashes are not interpreted as special characters (which is what happened to you in the first case).
How do I enclose a variable within single quotations in python? It's probably very simple but I can't seem to get it! I need to url-encode the variable term. Term is entered in a form by a user and is passed to a function where it is url-encoded term=urllib.quote(term). If the user entered "apple computer" as their term, after url-encoding it would be "apple%20comptuer". What I want to do is have the term surrounded by single-quotes before url encoding, so that it will be "'apple computer'" then after url-encoding "%23apple%20computer%23". I need to pass the term to a url and it won't work unless I use this syntax. Any suggestions?
Sample Code:
import urllib2
import requests
def encode():
import urllib2
query= avariable #The word this variable= is to be enclosed by single quotes
query = urllib2.quote(query)
return dict(query=query)
def results():
bing = "https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/Web?Query=%(query)s&$top=50&$format=json"
API_KEY = 'akey'
r = requests.get(bing % encode(), auth=('', API_KEY))
return r.json
There are four ways:
string concatenation
term = urllib.quote("'" + term + "'")
old-style string formatting
term = urllib.quote("'%s'" % (term,))
new-style string formatting
term = urllib.quote("'{}'".format(term))
f-string style formatting (python 3.6+)
term = urllib.quote(f"'{term}'")
You can just use string interpolation:
>>> term = "foo"
>>> "'%s'" % term
"'foo'"
For those that are coming here while googling something like "python surround string" and are time conscientious (or just looking for the "best" solution).
I was going to add in that there are now f-strings which for Python 3.6+ environments are way easier to use and (from what I read) they say are faster.
#f-string approach
term = urllib.parse.quote(f"'{term}'")
I decided to do a timeit of each method of "surrounding" a string in python.
import timeit
results = {}
results["concat"] = timeit.timeit("\"'\" + 'test' + \"'\"")
results["%s"] = timeit.timeit("\"'%s'\" % ('test',)")
results["format"] = timeit.timeit("\"'{}'\".format('test')")
results["f-string"] = timeit.timeit("f\"'{'test'}'\"") #must me using python 3.6+
results["join"] = timeit.timeit("'test'.join((\"'\", \"'\"))")
for n, t in sorted(results.items(), key = lambda nt: nt[1]):
print(f"{n}, {t}")
Results:
concat, 0.009532792959362268
f-string, 0.08994143106974661
join, 0.11005984898656607
%s, 0.15808712202124298
format, 0.2698059631511569
Oddly enough, I'm getting that concatenation is faster than f-string every time I run it, but you can copy and paste to see if your string/use works differently, there may also be a better way to put them into timeit than \ escaping all the quotes so let me know
Try it online!
def wrap_and_encode(x):
return encode("'%s'" % x)
Should be what you are looking for.
What's wrong with adding the single quotes after it being url encoded? Or, just adding them before hand in you encode function above?
I just stumbled upon some code doing it this way:
term = urllib.quote(term.join(("'", "'")))
(In this case join() uses term as a separator to combine all elements that were given in the iterable parameter into one string. Since there are only two elements, they are simply wrapped around one instance of term.)
Although it is quite readable, I would still consider it a hack and less readable than other options. Therefore, I recommend the use of string formatting as mentioned by others:
term = urllib.quote("'{}'".format(term))
I am trying to pass a string which has a '%' in it (its actually a sql query string). How do I pass the % (do I have to use a specific escape character?
eg:
compute_answertime("%how do I%")
Use another % to escape it
>>> compute_answertime("%%how do I%%")
use %%..........
You can use:
%%; DROP TABLE Students; --
Sorry, couldn't resist.