【问题标题】:Escape ":" in Python?在 Python 中转义“:”?
【发布时间】:2017-03-25 03:49:03
【问题描述】:

我正在使用 Python(和 Pytumblr)并尝试从一些返回的数据中提取某个字符串,但我正在搜索的字符串中包含“:”。每当我运行我的脚本时,我都会收到错误:

File "myfile.py", line 22
    if re.search('^ion': u'..', u'b', line) :
                       ^
SyntaxError: invalid syntax

这是我的代码:

import pytumblr
import re

returned = client.submission('blog') # get the submissions for a given blog

sch = open('returned')
for line in sch:
    line = line.rstrip()
    if re.search('^ion': u'..', u'b', line) :
        print line

此代码中是否还有其他错误,或者是否有办法逃脱我不知道的“:”?我对 Python 很陌生,但我不认为:需要转义。

【问题讨论】:

  • : 无所谓,但' 有关系。
  • 请提供您尝试匹配的数据示例。

标签: python escaping pytumblr


【解决方案1】:

这是一个语法错误,因为您的冒号不是字符串的一部分。单引号 ' 标记正在关闭字符串。您的第一个参数被解析为:

'^ion'       - String 1: ^ion
:            - Syntactical colon
 u           - The syntactical character u,
               indicating you intend for the
               following string literal to be
               in unicode
'..'         - String 2: ..

如果您希望 ^ion 末尾的单引号成为字符串的一部分,您需要使用反斜杠 '^ion\': 转义 that,或者使用双引号围绕字符串本身。由于 Python 接受字符串文字标记的单引号和双引号,'hello'"hello" 的含义相同。使'"hello world"'"'hello world'" 成为合法字符串。

如果正则表达式是这里的痛点,那么有很多文献和工具可以提供帮助。我推荐regex101

【讨论】:

    【解决方案2】:

    尝试使用双引号:

    re.search("^ion': u'..', u'b", line):
    

    或者转义'

    re.search('^ion\': u\'..\', u\'b', line):
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      相关资源
      最近更新 更多