字符串函数

本文介绍了使用Python进行字符操作和字符串匹配的方法,包括字符转换、字符串应用与匹配技巧,如输出特定格式的字符序列、匹配特定子串及前后缀等。

一、chr函数 & ord函数

#输出a01-z26的字样
x = ord("a")
print(x)		#输出97
i = 0
while i < 26:
	s = chr(x)
	if	len(str(i +1)) == 2:
		print(s + str(i + 1))
	else:
		print(s +  "0" +str(i + 1))	
	i += 1
	x += 1


二、字符串的应用&匹配

应用一
#字符串匹配
sub = "jeap"
s = "jeahello jeapedu.com"
i = 0
while i <= len(s) - len(sub):
	j = 0
	c = 0
	while j < len(sub):
		if	s[i + j] == sub[j]:
			c += 1
		j += 1
		if	c == len(sub):
			print(s[i],s[i+1],s[i+2],s[i+3])	#输出jeap
	i += 1
应用二
#je后面和du前面的字符
s = "hello jeapleoowedu.com"
head = "je"
tail = "du"
i = 0
pt = 0
while i <= len(s) - len(head):		#why <=
	j = 0
	ch = 0
	while j < len(head):			#why <
		if s[i + j] ==head[j]:
			ch += 1
		j += 1
	ct = 0
	j = 0
	while j < len(tail):
		if	s[i +j] == tail[j]:
			ct += 1
		j += 1
	if ch == len(head):
		ph = i
	if	ct == len(tail):
		pt =i
	i += 1
#print(ph,pt)
sub = ""
k = ph + len(head)
while k < pt:
	sub += s[k]
	k += 1
print(sub)



应用三、
head = "http"
tail = ".com"
s = "welcome to visit my websit http://www.baidu.com a.com c.com hehe http://163.com or http://www.sohu.com"
ph = 0
pt = 0
i = 0
preh = 0
while i <= len(s) - len(head):
	j = 0
	c =0
	while j < len(head):
		if s[i + j] == head[j]:
			c += 1
		j += 1
	if c == len(head):
		ph = i
		print("ph = ",ph)
	j = 0
	c = 0
	while j < len(tail):
		if s[i + j] == tail[j]:
			c += 1
		j += 1
	if c == len(tail):
		pt = i
		print("pt = ",pt)
		if ph < pt and	preh != ph:
			k = ph
			dns = ""
			while k < pt + len(tail):
				dns += s[k]
				k += 1
			print(dns)
			preh = ph
	i += 1
'''
输出结果:
pt =  43
http://www.baidu.com
pt =  49
pt =  55
ph =  65
pt =  75
http://163.com
ph =  83
pt =  98
http://www.sohu.com
'''


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值