字符串与正则表达式
- python字符串格式化知多少
1、字符串格式化的各种方法(4种)
(1)%格式化
(2)模版字符串
(3)字符串的format方法
(4)字符串的fstring方法
2、请解释什么是模版字符串,如何使用
#通过Template对象封装, $放置一些占位符,并通过subtitute方法用实际的值替换这些占位符
from string import Template
template1 = Template('$s是我最喜欢的编程语言,$s易学且功能强大')#s为占位符名字
print(template1.substitute(s = 'python'))
#若占位符名字后不是中文,如何区分占位符名字
template2 = Template('$hello world')
print(template2.substitute(hello='123'))
#print(template2.substitute(h='123'))#erro
template3 = Template('${h}ello world')
print(template3.substitute(h = '123'))
#也可以使用字典传入值,两个$$可以显示一个$,类似于转义符号
template4 = Template('$dollar$$等于$pounds英镑')
data = {}
data['dollar'] = 12
data['pounds'] = 34
print(template4.substitute(data))
- 使用fstring方式格式化字符串
1、在python中哪种格式化方法可以直接使用变量
fstring
2、请使用代码描述如何使用fstring格式化字符串
在fstring字符串中嵌入python变量
#fstring方法在python字符串中嵌入变量
name = 'bill'
age = 20
def GetAge():
return 21
s = f'我是{name},我今年{age}岁,明年{GetAge()}岁'
print(s)
#也可以引用对象里边的成员
class Person:
def __init__(self):
self.name = 'mike'
self.age1 = 40
def getage(self):
return 41
person = Person()
s1 = f'我是{person.name},我今年{person.age1}岁,明年{person.getage()}岁'
print(s1)
fstring方式就是在字符串中直接使用python变量,在字符串前面使用f标注,可以在一对儿大括号中嵌入python成员,这个成员可以是变量、函数、对象。
- 详细描述python字符串的基本操作
1、通过索引获取字符串中的某个字符
s = ‘hello world’
print(s[0])
print(s[3])
2、分片
print(s[6:9])
print(s[6:])
print(s[::2])
print(s[::-1])
3、多次输出字符串
print(10*s)
4、判断某个字符是否在字符串中
print(‘h’ in s)
print(‘h’ not in s)
5、函数(len,min,max)
以上函数同样可以用于列表中,列表与字符串的不同在于列表可以通过索引修改值,而字符串和元组一样不可修改,是只读的,可以将字符串理解为与字符组成的元组 - 详细描述向字符串的form方法传递参数的几种方式
1、字符串的format方法有几种指定参数的方式(3种)
默认方式(传入的参数与{}一一对应),命名参数和位置参数{2}
2、请详细描述字符串的format方法如何格式化字符串
#第一种:默认方式
s1 = 'today is {},the temperature is {} degrees'
print(s1.format('saturday',24))
#第二种:命名参数
s2 = 'today is {day},the temperature is {degree} degrees'
print(s2.format(day = 'sunday',degree = 30))
s3 = 'today is {day},{},the {} temperature is {degree} degrees'
print(s3.format('abdf',1234,day = 'saturday',degree = 24))
#第三种:位置参数,将format中对应位置的值传入字符串中
s4 = 'today is {day},{1},the {0} temperature is {degree} degrees'
print(s4.format('sdfdf',123589,day = 'saturday',degree = 24))
#引申
class Person:
def __init__(self):
self.age = 20
self.name = 'bill'
person = Person()
s5 = 'my name is {p.name},my age is {p.age}'
print(s5.format(p = person))
format方法使用一对{……}指定字符串需要替换的部分,在花括号中可以使用数字,表示引用特定位置的参数值,也可以使用标识符,也可以根据名字设置相应位置的占位符
-
让字符串居中显示
1、如何使字符串居中显示,有哪些方法
(1)center方法
(2)format方法
2、请使用center方法让字符串居中显示,两侧显示#号
print(’<’+‘hello’.center(30)+’>’)
print(’<’+‘hello’.center(30,’#’)+’>’)print(’<{:^30}>’,format(‘hello’))
print(’<{:#^30}>’,format(‘hello’)) -
连接列表中的分隔符
1、如何将列表中的元素(字符串类型的值)连接在一起(首尾相接)
a = [‘a’,‘b’,‘c’,‘d’,‘e’]
s = “+”
print(s.join(a))##a+b+c+d+e
2、字符串的join方法的作用是什么,使用join应该注意些什么,请举例说明
作用:用于连接列表中的元素值
##连接路径
dirs = ‘’,‘usr’,‘local’,‘der’
print(dirs)
linuxpath = ‘/’.join(dirs)
windowspath = ‘c:’+’\’.join(dirs)
注意:join连接列表里元素的类型必须是字符串类型,如果不是需要转换一下 -
用正则表达式判断字符串中是否包含日期
1、请简要描述python正则表达式中match函数的作用
match函数的作用,match属于re模块,匹配一个字符串是否和一个正则表达式
import re
print(re.match(’.*hello’,‘ahello’))
2、如果日期的格式是4位年,2位月,2位日(如2012-01-02),如何使用正则表达式判断一个字符串中是否包含这样的日期
import re
s = 'today is 2014-04-23.'
m = re.match('.*\d{4}-\d{2}-\d{2}.*',s)
if m is not None:
print(m.group())
- 寻找字符串中的手机号
1、请描述python正则表达式中match和search的区别
match:用于匹配
search:用于搜索
import re
m1 = re.match(’.*python’,‘i love python’)
print(m1)
m2 = re.search(‘python’,‘i love python’)
print(m2)
search用于搜索后边字符串中满足前边正则表达式的内容,match用于根据前边正则表达式匹配后边整个字符串
2、如果一个字符串中含有11位的手机号,请使用正则表达式找到第1个出现的手机号,并输出手机号,开始索引和结束索引
m = re.search('1\d{10}','我的手机号是12311302033')
if m is not None:
print(m.group())
print(m.start())
print(m.end())
- 用正则表达式分别提取电话号的区号、电话号和分机号
1、如何搜索字符串中包含的区号和分机号的第一个出现的电话号,并提取电话号中的区号、电话号和分机号,格式类似于024-12345678-3456
正则表达式,圆括号
import re
m = re.search('(\d{3})-(\d{7,})-(\d{3})','我的座机号是024-12345678-1234')
#{7,}加逗号表示至少7位
if m is not None:
print(m.group())
print(m.groups())
print(m.groups()[0])
print(m.groups()[1])
print(m.groups()[2])
通过在正则表达式的某些部分加一对圆括号,可以单独获取圆括号中的内容,这称为正则表达式的分组
- 用正则表达式查找字符串中所有的email
1、用正则表达式查找字符串中所有的email,并输出这些email,要求所有的email域名必须是.com或.net,而且不区分大小写
import re
s = '我的Email地址是abcd@163.com,你的Email是多少呢?是xyz@126.net,还是ccc@123.org呢?'
perfix = ('[0-9a-zA-Z]+@[0-9a-zA-Z]+\.')
result = re.findall(perfix + 'com|'+perfix + 'net',s,re.I)#re.I表示忽略大小写
print(result)
findall函数用于搜索字符串中所有满足条件的子字符串,该函数的第一个参数用于指定正则表达式,第2个参数用于指定带匹配的字符串,第3个参数用于指定选项,如re.I表示忽略大小写。
- 用正则表达式格式化字符串中所有的浮点数
1、用正则表达式查找字符串中所有的浮点数,并格式化这些浮点数,保留小数点后2位,最后将格式化后的浮点数替换原来的浮点数,同时输出替换后的结果和替换的次数,要求用一条语句实现
import re
def fun(matched):
return format(float(matched.group()),'0.2f')
result = re.subn('-?\d+(\.\d+)?',fun,'PI is 3.1415926, e is 2.71828183,-0.8+1.3 = 2.1')
print(result)
print(result[0])
sub和subn都用于替换字符串中所有符合条件的子字符串,但sub函数只返回替换后的结果,而subn返回一个元组,元组的第一个元素返回替换后的结果,第2的元素返回替换的次数
- 提取HTML页面中的URL
1、提取HTML页面中所有的Url,要求,这些Url都属于a节点的href属性
import re
s = '<a href="https://geekori.com">极客起源</a> <a href="https://www.microsoft.com">微软</a>'
result = re.findall('<a[^>*]href="([^>]*)">',s,re.I)#利用分组提出href的属性值(Url)
print(result)
for url in result:
print(url)