简体   繁体   English

删除字符串中的字符“'s”

[英]remove character " 's " in string

Suppose there are character 's at the end of word, how can I remove it?假设单词末尾有字符's ,我该如何删除它?

Below, is what I tried:下面,是我尝试过的:

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, "")

Output should be: "s'ss python is fun"输出应该是:“ss 的 python 很有趣”

Somehow it will remove all s and ' , not just at the end.不知何故,它会删除所有s' ,而不仅仅是在最后。

How can I just remove the character that have " 's ".我怎样才能删除具有“'s”的字符。

I think this accomplishes what you're looking for (sorry if I misunderstood :) ).我认为这可以完成您正在寻找的内容(对不起,如果我误解了:))。 This splits your string on whitespace and then iterates through the resulting 'words'.这会在空格上拆分您的字符串,然后遍历生成的“单词”。 If the word ends in 's , that part is removed;如果单词以's结尾,则删除该部分; if not, the entire word is returned.如果不是,则返回整个单词。 The result is then joined with the space character to return a string:然后将结果与空格字符连接以返回一个字符串:

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"
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'"

I'd use regular expressions, like this:我会使用正则表达式,如下所示:

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

( \\b matches the beginning or end of a word) \\b匹配单词的开头或结尾)

First, your st ends with a space - you probably want to remove this with either str.split orstr.lstrip :首先,您的st以空格结尾 - 您可能想用str.splitstr.lstrip删除它:

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

Then to remove the trailing 's there are many different ways.然后删除尾随's有很多不同的方法。

Using a regular expression is one tidy way:使用正则表达式是一种整洁的方式:

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

Or you can check if the string ends with 's and remove the last two characters:或者您可以检查字符串是否以's结尾并删除最后两个字符:

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

Do not usestr.rstrip to do this, as it may not act like you may expect:不要使用str.rstrip来执行此操作,因为它可能不会像您期望的那样:

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

Looks correct in this case, but as the docs explain, "[the] argument is not a suffix; rather, all combinations of its values are stripped".在这种情况下看起来是正确的,但正如文档所解释的那样,“[the] 参数不是后缀;相反,它的值的所有组合都被剥离了”。 For example:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM