【问题标题】:How to replace ™ in a string?如何替换字符串中的™?
【发布时间】:2018-10-14 07:28:44
【问题描述】:

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

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

我在文件最上面加了:# -- coding: 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

【问题讨论】:

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


【解决方案1】:

替换不起作用,因为第二次调用str.replace() 返回值没有分配给任何东西,所以它丢失了。您可以通过以下方式修复它:

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

但是,要将返回值绑定到 temp_title,请考虑以下事项。

由于您想对字符串进行百分比编码以在 URL 中使用,您可以简单地使用 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'

【讨论】:

    【解决方案2】:

    我使用了 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
    

    【讨论】:

      【解决方案3】:

      我认为你使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-03
        • 2023-04-09
        • 1970-01-01
        • 2013-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多