简体   繁体   English

如何在有约束的python中切片特定字符?

[英]how to slice specific characters in python with constraints?

str="class computer :"
name=str[str.find("class"):str.find(":")]
print name

The above code has to output the result as " computer " for which I get, "class computer" . 上面的代码必须将结果输出为我得到的" computer " ,即"class computer" what might be the mistake? 可能是什么错误?

Once you .find('class') you need to offset that index by the length of the string 'class' itself. 一旦找到.find('class') ,就需要使该索引偏移字符串'class'本身的长度。

>>> s = 'class computer :'
>>> s[s.find('class')+len('class'):s.find(':')]
' computer '

You could throw on a strip to remove the leading and trailing whitespace 您可以丢下一条strip以删除开头和结尾的空格

>>> s[s.find("class")+len('class'):s.find(":")].strip()
'computer'

str.find returns the index of the first occurring character match and hence 0 is returned str.find返回第一个出现的字符匹配项的索引,因此返回0

>>> s.find('class')
0

From the docs 来自文档

Return the lowest index in the string where substring sub is found 返回找到子字符串sub的字符串中的最低索引

Thus you need to add the length of your find string to get the correct output by using the len function 因此,您需要使用len函数添加find字符串的长度以获取正确的输出

>>> name=s[s.find("class")+len('class'):s.find(":")]
>>> print name
 computer 

Note - You should not use str as a variable as it shadows the built-in functionality 注意-您不应将str用作变量,因为它会掩盖内置功能

If you have any other word with class in it your find will fail, you can use a regex with word boundaries to find an exact match for the word class : 如果您在class中有其他单词,则查找将失败,您可以使用带有单词边界的正则表达式来查找单词class的完全匹配class

import  re

print(re.findall(r"(?<=\bclass\b)\s+\w+\s+",s))

You can see an example of how it will fail: 您可以看到一个示例,该示例将如何失败:

In [9]: s = "subclass class computer :"

In [10]: s[s.find('class')+len('class'):s.find(':')]
Out[10]: ' class computer '

In [11]: re.findall(r"(?<=\bclass\b)\s+\w+\s+",s)
Out[11]: [' computer ']

If you have more than one class in your string you can use a lookahead with the lookbehind assertion: 如果您的字符串中有多个class ,则可以在lookbehind断言中使用lookahead:

 s = "subclass class tv class computer :"
 print(re.findall(r"(?<=\bclass\b)\s+\w+\s+(?=:)",s))

 [' computer ']

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

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