Python编程基础与列表操作全解析
1. 使用split()函数比较单词
在Python中, split() 函数可用于将字符串拆分为单词列表,进而与其他单词进行比较。以下是一个示例代码 Compare2.py :
x = 'This is a string that contains abc and Abc'
y = 'abc'
identical = 0
casematch = 0
for w in x.split():
if(w == y):
identical = identical + 1
elif (w.lower() == y.lower()):
casematch = casematch + 1
if(identical > 0):
print('found identical matches:', identical)
if(casematch > 0):
print('found case matches:', casematch)
if(casematch == 0 and identical == 0):
print('no matches found')
此代码通过 split() 函数将字符串 x 拆分为单词列表,然后逐个与单词 abc 进行比较。若完全匹配, identical 变量加1;若不区分大小写匹配, casematch
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



