【问题标题】:How to fix this error when using the str.index() method?使用 str.index() 方法时如何解决此错误?
【发布时间】:2019-09-06 18:03:37
【问题描述】:

我有一个文本字符串-“该类还包含集合标题的字符串和一个标量布尔变量,指示集合当前是否可编辑。”

在这里,我正在尝试获取子字符串“collection's”的索引,但出现以下错误。 ValueError: 未找到子字符串

我了解实际文本中子字符串中的撇号使用不同的字体。那么,有什么方法可以绕过字体差异。

txt = "The class also contains a string for the collection’s title and a scalar Boolean variable indicating whether the collection is currently editable."

print(txt.index("collection's"))

期望是有子字符串的索引-“集合的”

实际结果是:ValueError: substring not foundenter code here

【问题讨论】:

  • Python 中的字符串文字没有任何“字体”;如果两个角色看起来不同,那是因为他们是不同的角色。您可以像这样用普通的撇号替换花哨的撇号:txt = txt.replace("’", "'")
  • 如前所述,这些是不同的字符。如果你遇到这样的情况,你可以使用== 运算符来检查字符是否相同——在这种情况下print("’"=="'") 输出False

标签: python python-3.x


【解决方案1】:

这是因为'是不同的字符

【讨论】:

    【解决方案2】:

    只需确保您的文本和您要查找的字符串使用相同形式的撇号'

    txt = "The class also contains a string for the collection's title and a scalar" \
       "Boolean variable indicating whether the collection is currently editable."
    print(txt.index("collection's"))
    #41
    

    【讨论】:

    • 感谢@Devesh 的回复。但是,如果可用的文本很大怎么办。并且个人不知道现在的撇号是:“'”还是“'”
    • 只需运行text.replace('’',"'")
    猜你喜欢
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2012-01-28
    • 1970-01-01
    • 2015-10-12
    相关资源
    最近更新 更多