Python字符串匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3351218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:36:29  来源:igfitidea点击:

Python string match

regexstringpython

提问by Rajeev

If a string contains *SUBJECT123, how do I determine that the string has subjectin it in python?

如果字符串包含*SUBJECT123,我如何确定该字符串subject在 python 中是否存在?

采纳答案by ghostdog74

if "subject" in mystring.lower():
  # do something

回答by Felix Kling

If you want to have subjectmatch SUBJECT, you could use re

如果你想有subject比赛SUBJECT,你可以使用re

import re
if re.search('subject', your_string, re.IGNORECASE)

Or you could transform the string to lower case first and simply use:

或者您可以先将字符串转换为小写,然后简单地使用:

if "subject" in your_string.lower()

回答by Douglas Leeder

if "*SUGJECT123" in mystring and "subject" in mystring:
    # do something

回答by Ankit Jaiswal

Just another way

只是另一种方式

mystring.find("subject")

the above answers will return true if the string contains "subject" and false otherwise. While find will return its position in the string if it exists else a negative number.

如果字符串包含“主题”,则上述答案将返回 true,否则返回 false。如果 find 存在,则 find 将返回其在字符串中的位置,否则为负数。