I have a string looks like this: Getting Started with NetX™ DHCP rev1.05
I want to replace TM with %E2%84%A2.
I added:# -- coding: utf-8 -- to the very top of the file, still not work, no errors pop up
I am using Python 2.7
Here's my python code:
def create_link(title):
temp_title = title.replace(' ', '%20') # first replace space with %20. works fine
temp_title.replace('™', '%E2%84%A2') # then replace TM, not working
link = 'https://ApplicationNotes/'+ temp_title
return link
The replacement does not work because for the second call to str.replace()
the return value is not assigned to anything, so it is lost. You could fix it with:
temp_title = temp_title.replace('™', '%E2%84%A2')
to bind the return value to temp_title
, however, consider the following.
Since you want to percent encode the string for use in a URL you can simply use urlib.quote()
:
>>> title = 'NetX™ DHCP rev1.05'
>>> title
'NetX\xe2\x84\xa2 DHCP rev1.05'
>>> import urllib # Python 2
>>> urllib.quote(title)
'NetX%E2%84%A2%20DHCP%20rev1.05'
You'll notice that the spaces have also been handled for you. So you could write your function like this:
def create_link(title):
return urllib.quote('https://ApplicationNotes/{}'.format(title))
which has the advantage of also percent encoding other eligible characters in the URL.
For completeness, if you were using Python 3:
>>> from urllib.parse import quote
>>> quote('NetX™ DHCP rev1.05')
'NetX%E2%84%A2%20DHCP%20rev1.05'
You might not even need to quote URL depending on what you want to do with it. If you are using requests
to send a HTTP request for the URL you can just use it as is:
>>> import requests
>>> r = requests.get('https://ApplicationNotes/NetX™ DHCP rev1.05')
>>> r.url
u'https://ApplicationNotes/NetX%E2%84%A2%20DHCP%20rev1.05'
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加