【问题标题】:remove character " 's " in string删除字符串中的字符“'s”
【发布时间】:2012-11-24 23:31:47
【问题描述】:

假设单词末尾有字符's,我该如何删除它?

下面是我尝试过的:

st = "s'ss python's is fun's "
for ch in st:
    if ch[-2:] in "'s":   # check if last two index is 's
        st = st.replace(ch, "")

输出应该是:“sss python is fun”

它会以某种方式删除所有s',而不仅仅是在最后。

我怎样才能删除有“的”字符。

【问题讨论】:

  • for ch in st: 循环遍历每个字符,而不是您想要的行为。

标签: python python-3.2


【解决方案1】:

我认为这可以满足您的需求(如果我误解了 :) ,请原谅)。这会将您的字符串拆分为空格,然后遍历生成的“单词”。如果单词以's 结尾,则删除该部分;如果不是,则返回整个单词。然后将结果与空格字符连接以返回一个字符串:

In [16]: st = "s'ss a python's is fun's "

In [17]: ' '.join(s if s[-2:] != "'s" else s[:-2] for s in st.split())
Out[17]: "s'ss a python is fun"

【讨论】:

    【解决方案2】:
    mylist = []
    strin = "s'ss hello you's"
    mylist = list(strin)
    mylist.remove[-1]
    print str(mylist)
    #the output will be as , "s'ss hello you'"
    

    【讨论】:

      【解决方案3】:

      我会使用正则表达式,像这样:

      >>> import re
      >>> re.sub(r"'s\b", "", "s'ss python's ")  
      "s'ss python "
      

      \b 匹配单词的开头或结尾)

      【讨论】:

        【解决方案4】:

        首先,您的 st 以空格结尾 - 您可能希望使用 str.splitstr.lstrip 删除它:

        >>> st = "s'ss python's is fun's "
        >>> st = st.strip()
        >>> print(st)
        s'ss python's is fun's
        

        那么去除尾随的's有很多不同的方法。

        使用正则表达式是一种简洁的方式:

        >>> import re
        >>> re.sub("'s$", "", st)
        "s'ss python's is fun"
        

        或者您可以检查字符串是否以's 结尾并删除最后两个字符:

        >>> if st.endswith("'s"):
        ...     st = st[:-2]
        

        请勿使用str.rstrip 来执行此操作,因为它的行为可能与您预期的不同:

        >>> st.rstrip("'s") # Bad
        "s'ss python's is fun"
        

        在这种情况下看起来是正确的,但正如文档解释的那样,“[the] 参数不是后缀;相反,它的所有值组合都被剥离了”。例如:

        >>> "lots of ssssss's".rstrip("'s")
        'lots of '
        

        【讨论】:

          猜你喜欢
          • 2016-07-04
          • 1970-01-01
          • 2016-08-29
          • 1970-01-01
          • 1970-01-01
          • 2021-01-17
          • 2015-11-20
          • 2016-07-26
          相关资源
          最近更新 更多