Python 检查项目符号是否在列表中
因此,我试图通过使用for循环对项目进行迭代来检查项目符号是否是列表中项目的一部分。我知道,至少在正则表达式中,一个要点被定义为Python 检查项目符号是否在列表中,python,list,Python,List,因此,我试图通过使用for循环对项目进行迭代来检查项目符号是否是列表中项目的一部分。我知道,至少在正则表达式中,一个要点被定义为\u2022。但我不知道怎么用这个。我目前拥有但显然不起作用的是这样的东西 list = ['changing. • 5.0 oz.', 'hello', 'dfd','df', 'changing. • 5.0 oz.'] for items in list: if "\u2022" in items: print('yay') 提前谢谢
\u2022
。但我不知道怎么用这个。我目前拥有但显然不起作用的是这样的东西
list = ['changing. • 5.0 oz.', 'hello', 'dfd','df', 'changing. • 5.0 oz.']
for items in list:
if "\u2022" in items:
print('yay')
提前谢谢 最好使用
re
(regex)库。大概是这样的:
# import regex library
import re
# compile the regex pattern, using raw string (that's what the r"" is)
bullet_point = re.compile(r"\u2022")
list = ['changing. • 5.0 oz.', 'hello', 'dfd','df', 'changing. • 5.0 oz.']
# search each item in the list
for item in list:
# search for bullet_point in item
result = re.search(bullet_point, item)
if result:
print('yay')
在。如果你打算使用Unicode很多,考虑切换到Python 3。
在中,您必须通过在字符串前面加上u
来明确声明哪些字符串是Unicode
首先,将源代码编码设置为UTF-8
# -*- coding: utf-8 -*-
然后告诉Python将这些字符串编码为Unicode。否则,它们将被视为单个字节,这将导致一些奇怪的事情,比如Python认为第一个字符串的长度是21而不是19
print len(u'changing. • 5.0 oz.') # 19 characters
print len('changing. • 5.0 oz.') # 21 bytes
这是因为。第一个字符将其视为单个字符,第二个字符将其视为三个字节
最后,将要搜索的字符编码为Unicode。这是u'\u2022'
或u'•'
#!/usr/bin/env python
# -*- coding: utf-8 -*-
list = [u'changing. • 5.0 oz.', u'hello', u'dfd', u'df', u'changing. • 5.0 oz.']
for item in list:
if u'•' in item:
print('yay')
真正的代码可能不会使用常量字符串,因此您必须确保
列表中的任何内容都编码为UTF-8。这是Python 2还是Python 3?您的代码对我来说很好。虽然这可以工作,但对于简单的字符搜索和对编码问题的研究来说,这是一种过分的方法。非常正确,我经常忘记您可以将python编码为UTF-8
# -*- coding: utf-8 -*-