Python 等效于包含的 unicode 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29456800/
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-19 04:34:49  来源:igfitidea点击:

unicode string equivalent of contain

pythonstringunicode

提问by aceminer

I have an error when trying to use contain in python.

尝试在 python 中使用包含时出错。

s = u"some utf8 words"
k = u"one utf8 word"

if s.contains(k):
    print "contains" 

How do i achieve the same result?

我如何达到相同的结果?

Example with normal ASCII string

带有普通 ASCII 字符串的示例

s = "haha i am going home"
k = "haha"

if s.contains(k):
    print "contains"

I am using python 2.7.x

我正在使用 python 2.7.x

采纳答案by frnhr

The same for ascii and utf8 strings:

ascii 和 utf8 字符串相同:

if k in s:
    print "contains" 

There is no contains()on either ascii or uft8 strings:

contains()ascii 或 uft8 字符串都没有:

>>> "strrtinggg".contains
AttributeError: 'str' object has no attribute 'contains'


What you can use instead of containsis findor index:

您可以使用的containsfindor index

if k.find(s) > -1:
    print "contains"

or

或者

try:
    k.index(s)
except ValueError:
    pass  # ValueError: substring not found
else:
    print "contains"

But of course, the inoperator is the way to go, it's much more elegant.

但是当然,in运算符是要走的路,它要优雅得多。

回答by Daniel

There is no difference between strand unicode.

str和之间没有区别unicode

print u"ábc" in u"some ábc"
print "abc" in "some abc"

is basically the same.

基本上是一样的。

回答by Ajay

Strings don't have "contain" attribute.

字符串没有“包含”属性。

s = "haha i am going home"
s_new = s.split(' ')
k = "haha"

if k in s_new:
    print "contains"

I guess you want to achieve this

我猜你想实现这一目标

回答by Harvey

Testing of string existance in string

字符串中字符串存在的测试

string = "Little bear likes beer"
if "beer" in string:
    print("Little bear likes beer")
else:
    print("Little bear is driving")