如何更换弦乐?

时间:2018-05-03 21:43:15

标签: python string python-2.7 unicode python-unicode

我有一个字符串如下:NetX™DHCP rev1.05入门

我想用%E2%84%A2替换TM。

我补充说:# - - 编码:utf-8 - - 到文件的最顶层,仍然无效,没有错误弹出

我正在使用Python 2.7

这是我的python代码:

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

3 个答案:

答案 0 :(得分:3)

替换不起作用,因为对str.replace()的第二次调用,返回值未分配给任何内容,因此它将丢失。您可以使用以下方法修复它:

temp_title = temp_title.replace('™', '%E2%84%A2')

将返回值绑定到temp_title,但请考虑以下内容。

由于您希望对字符串进行百分比编码以便在网址中使用,因此您只需使用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'

你会注意到这些空间也已经为你处理了。所以你可以这样编写你的函数:

def create_link(title):
    return urllib.quote('https://ApplicationNotes/{}'.format(title))

,其优点还在于对URL中其他符合条件的字符进行编码百分比。

为了完整性,如果您使用的是Python 3:

>>> from urllib.parse import quote
>>> quote('NetX™ DHCP rev1.05')
'NetX%E2%84%A2%20DHCP%20rev1.05'

您可能根本不需要引用URL,具体取决于您要对其执行的操作。如果您使用requests发送URL的HTTP请求,您可以按原样使用它:

>>> import requests
>>> r = requests.get('https://ApplicationNotes/NetX™ DHCP rev1.05')
>>> r.url
u'https://ApplicationNotes/NetX%E2%84%A2%20DHCP%20rev1.05'

答案 1 :(得分:0)

我认为您使用re模块:

import re
def create_link(title):
  temp_title = title.replace(' ', '%20') # first replace space with %20. works fine
  temp_title = re.sub(r'™', r'%E2%84%A2', temp_title) # this change
  link = 'https://ApplicationNotes/'+ temp_title
  return link

答案 2 :(得分:-1)

我使用了python 3.4,这段代码对我有用。请将第3行更改为temp_title = temp_title.replace('™', '%E2%84%A2')

def create_link(title):
    temp_title = title.replace(' ', '%20')
    temp_title = temp_title.replace('™', '%E2%84%A2')
    link = 'https://ApplicationNotes/'+ temp_title
    return link