ディレクトリ
- 文字列の書式テンプレート文字列
- フォーマット文字列を使用した方法をFstring
- 文字列の基本的な操作
- いくつかの方法でフォーマット文字列パラメータへの送達方法
- 文字列が中央にしてみましょう
- 接続リスト内の要素の値
- 正規表現は、日付文字列がかどうかが決定されると、
- 電話番号の文字列を探して
- それぞれの正規表現で抽出市外局番電話番号、電話番号と内線番号、
- 正規表現の検索文字列のすべての電子メールと
- すべての浮動小数点形式の文字列のための正規表現
- HTMLページのURLを抽出
01.文字列の書式テンプレート文字列
書式文字列によって:
- フォーマット%
- テンプレート文字列
- formatメソッド
- fstring
# 模板字符串
# 通过Template对象封装,用 $ 放置一些占位符,并通过substitute方法用实际的值替换这些占位符
from string import Template
template1 = Template('$s真棒,$s真厉害') # '$s真棒,$s真厉害' 就是模板字符串
print(template1.substitute(s = '我')) # 我真棒,我真厉害
print(template1.substitute(s = '你')) # 你真棒,你真厉害
template2 = Template('${h}ello world') # 用{}将占位符名称括起来,以便和其他单词区分
print(template2.substitute(h = 'abc'))
template3 = Template('$dollar$$相当于$pound£') # 若要输出$符号,则用$$
data = {}
data['dollar'] = 20
data['pound'] = 15.3
print(template3.substitute(data)) # 数据可放到字典中,更方便
概要
02.使用fstringモードのフォーマット文字列
# fstring
name = 'Bill'
age = 20
def toAge():
return age + 1
s = f'我是{name},今年{age}岁,明年我{toAge()}岁' #前面加上 f 表明有变量或函数
print(s)
我是Bill,今年20岁,明年我21岁
class Person:
def __init__(self):
self.name = 'Mike'
self.age = 40
def getAge(self):
return self.age + 1
person = Person()
s1 = f'我是{person.name},今年{person.age}岁,明年我{person.getAge()}岁' #对象内的成员也可以
print(s1)
我是Mike,今年40岁,明年我41岁
概要
03.文字列の基本的な操作
# 1:通过索引获取字符串中的某个字符(串)
s1 = 'hello world'
print(s1[1])
# 分片
print(s1[6:9])
print(s1[::2])
# 乘法,重复输出
print(s1 * 2)
# 字符是否在字符串中
print('b' in s1)
print('b' not in s1)
# 获取字符串长度、最大最小值
print(len(s1))
print(max(s1))
print(min(s1))
# 列表同样有用
# 但字符串不可以通过索引修改
04.いくつかの方法がありますフォーマット文字列にパラメータを渡す方法
# 默认方式(传入的参数与{}一一对应)、命名参数和位置参数
# 第二题
s1 = 'Today is {},the temperature is {} degree.'
print(s1.format('Sat', 20))
Today is Sat,the temperature is 20 degree.
s2 = 'Today is {day},the temperature is {degree} degree.'
print(s2.format(degree= 20, day= 'Sun'))
Today is Sun,the temperature is 20 degree.
s3 = 'Today is {day},{},the {} temperature is {degree} degree.'
print(s3.format('abcd', 1234, degree= 24, day= 'Sun'))
Today is Sun,abcd,the 1234 temperature is 24 degree.
s4 = 'Today is {day},{1},the {0} temperature is {degree} degree.'
print(s4.format('abcd', 1234, degree= 24, day= 'Sun'))
Today is Sun,1234,the abcd temperature is 24 degree.
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))
My name is Bill,my age is 20.
概要
05.文字列が中央にしてみましょう
# 1:center方法、format方法
# 2:
print('<' + 'hello'.center(30) + '>')
print('<' + 'hello'.center(30, '#') + '>')
<############hello#############>
print('<{:^30}>'.format('hello'))
print('<{:#^30}>'.format('hello'))
<############hello#############>
概要
リスト中の06の連結要素値
a = ['a', 'b', 'c', 'd', 'd']
s = '+'
print(s.join(a)) #用s分割a
a+b+c+d+d
# 作用:连接路径
dirs = 'D:', 'A', 'code', 'python', 'test'
print(dirs) # 元组 ('D:', 'A', 'code', 'python', 'test')
path = '\\'.join(dirs)
print(path) # D:\A\code\python\test
# 注意:连接的元素必须是字符串类型
n = [1, 2, 3, 4]
s = '+'
print(s.join(n))
Traceback (most recent call last):
File "D:/A/test.py", line 3, in <module>
print(s.join(n))
TypeError: sequence item 0: expected str instance, int found
概要
07.正規表現文字列を決定した日付が含まれています
import re # 专门处理正则表达式
print(re.match('hello', 'hello'))
<_sre.SRE_Match object; span=(0, 5), match='hello'>
print(re.match('hello', 'ahello'))
None # 不匹配返回None
print(re.match('.hello', 'ahello')) # . 表示任意字符
<_sre.SRE_Match object; span=(0, 6), match='ahello'>
print(re.match('.*hello', 'aahello')) # * 表示任意数量
<_sre.SRE_Match object; span=(0, 7), match='aahello'>
# 第二题
s = 'Today is 2020-02-06.'
m = re.match('.*\d{4}-\d{2}-\d{2}.*', s) # \d表示数字 {4}表示四位
if m is not None:
print(m.group())
Today is 2020-02-06.
08.電話番号の文字列を探して
違い:一致する一致、検索の検索
import re
print(re.match('.*python', 'i love python'))
<_sre.SRE_Match object; span=(0, 13), match='i love python'>
print(re.search('python', 'i love python'))
<_sre.SRE_Match object; span=(7, 13), match='python'>
# 搜索手机号
n = re.search('1\d{10}', 'phone number:12345487899') # 限制第一位为 1
if n is not None:
print(n.group())
print(n.start())
print(n.end())
12345487899
13
24
概要
09.は、それぞれ、正規表現との電話番号の市外局番、電話番号と内線番号を取得するには
# 正则表达式分组
import re
n = re.search('(\d{3})-(\d{7,})-(\d{3,})', 'phone number:024-123456789-5446')
#至少7位用 {7,},分组用()括起来并且用 n.groups
if n is not None:
print(n.group()) # 024-123456789-5446
print(n.groups()) # ('024', '123456789', '5446')
print(n.groups()[0]) # 024
print(n.groups()[1]) # 123456789
print(n.groups()[2]) # 5446
概要
10.メールの全てに正規表現の検索文字列を使用して
import re
n = '我的email地址是[email protected],你的地址是多少?是[email protected]吗?还是[email protected]?'
prefix = '[0-9a-z]+@[0-9a-zA-Z]+\.'
result = re.findall(prefix + 'com|' + prefix + 'net', n, re.I) # I 忽略大小写
# 'com|' 或后面要加完整的正则表达式 不能直接加'net',要不然就把'net'当条件
print(result)
['[email protected]', '[email protected]']
概要
11.すべての浮動小数点フォーマット文字列の正規表現
import re
'''
1.如何用正则表达式表示浮点数 考虑负数: -?\d+(\.\d+)? (-?表示可能有或没有负数,(\.\d+)?表示可能有或没有小数)
2.格式化浮点数 format
3.如何替换原来的浮点数 sub:只返回替换的结果 subn:返回元组(替换的结果, 替换的次数)
'''
result = re.subn('-?\d+(\.\d+)?', '##', 'Pi is 3.14159265, e is 2.71828183, -0.1 + 1.3 = 1.1')
print(result) # ('Pi is ##, e is ##, ## + ## = ##', 5)
print(result[0]) # Pi is ##, e is ##, ## + ## = ##
print(result[1]) # 5
def fun(match):
return '<' + match.group() + '>'
result = re.subn('-?\d+(\.\d+)?', fun, 'Pi is 3.14159265, e is 2.71828183, -0.1 + 1.3 = 1.1')
print(result) #('Pi is <3.14159265>, e is <2.71828183>, <-0.1> + <1.3> = <1.1>', 5)
def fun(match):
return format(float(match.group()), '0.2f')
result = re.subn('-?\d+(\.\d+)?', fun, 'Pi is 3.14159265, e is 2.71828183, -0.1 + 1.3 = 1.1')
print(result)
# ('Pi is 3.14, e is 2.72, -0.10 + 1.30 = 1.10', 5)
概要
12.抽出HTMLページのURL
import re
s = '<a href="www.baidu.com">百度</a> <a href="www.google.com">谷歌</a>'
result = re.findall('<a[^<]*href="([^<]*)">', s, re.I) #a和href中可能有除了<外的其他东西 [^<}
print(result)
['www.baidu.com', 'www.google.com']
for url in result:
print(url)
www.baidu.com
www.google.com
概要