3、Python编程基础与列表操作全解析

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值