Python学习笔记5(字符串与正则表达式)

1.字符串

1.1字符串的格式化

 #格式化语法
"%s" % str1
 "%s %s" % (str1,str2) 
#格式化字符串 

str1 = "version" 
num = 1.0
 format = "%s" % str1 
print (format) 
format = "%s %d" %(str1, num) 
print (format)

 

#使用字典格式化字符串 
print ("%(version)s: %num).1f" %{"version": "version", "num": 2})              #version:2.0 
#字符串对齐
word = "version3.0"                       #10个字符 
print (word.center(20))                   #在20字符宽度中位于中间。因此,输出:version3.0 两边各5个空格 
print (word.center(20, "*"))            #*****version3.0***** 
print (word.ljust(0)))                      #ljust()使输出结果左对齐 
print (word.rjust(20))                     #在20字符宽度中右对齐 
print("%30s" % word)                    # "%30" 表示先输出30个空格

 

 1.2字符串的转义符

转义符设定及其输出类似于C。

 #r的特殊用法 
path = r"hello\tworld\n" 
print (path)                                            #hello\tworld\n 
#strip()去掉转义字符 
word = "\thello world\n" 
print ("strip()后输出:", word.strip())                       #strip()后输出:hello world (去掉了转义字符后输出) 
print ("lstrip()后输出:", word.lstrip())                     #lstrip()后输出:hello world (去掉了句首转义字符\t,句尾\n保留) 
print ("rstrip()后输出:", word.rstrip())                     #rstrip()后输出:hello world(去掉了\n,保留句尾句首转义字符\t)

1.3字符串的合并

可以直接使用“+”连接两个字符串,也可使用如下几种方法。

# 使用join()连接字符串
strs = ["hello ", "world ", "hello ", "China "]
result = "".join(strs)
print result                       #hello world hello China
# 使用reduce()连接字符串
from functools import reduce
import operator
strs = ["hello ", "world ", "hello ", "China "]
result = reduce(operator.add, strs, "")
print (reduce)

字符串连接后,Python将分配新的空间给连接后的字符串,源字符串保持不变。

str1 ="a"
print (id(str1))
print (id(str1 + "b"))                           # 输出结果不同

1.4字符串的截取

 可以使用索引截取字符串,也可使用如下方法。

# 切片语法
string[start: end: step]                    # 从第start个索引到第end个索引,步长为step          

# 特殊切片截取子串
str1 = "hello world"
print (str1[0:3])                 # hell
print (str1[::2])                  # hlowrd
print (str1[1::2])                # el ol"
# split()函数
split([char] [,num])                             
# char表示用于分割的字符,默认为空格
# num表示分割的次数。若num=2,分割为3个字符 
# 默认情况下,根据char在字符中出现字数来分割子串
# 函数的返回值为由子串组成的列表

# 使用split()获取子串
sentence = "Bob said: 1, 2, 3, 4"
print (sentence.split())              # 使用空格分割  ['Bob', 'said:', '1,', '2,' '3', '4']
print (sentence.split(","))           # 使用逗号分割
print (sentence.split(",",2))        # 使用两个逗号分割   
# ['Bob said: 1', '2' '3, 4']         费解!!!
 

1.5字符串的比较

可直接使用“==”与“!=”比较两个字符串。

要比较字符串的开头或结尾部分,可使用startswith()或endswith()函数

# startswith()
startswith(substring, [,start [,end]])
# substring是与源字符串开头部分比较的子串
# start表示开始位置,end表示结尾位置
# 若字符串以substring开头,返回True

# 用法
word = "hello world"
print ("hello" == word[0:5])
print (word.startswith("hello")
print (word.endwith("ld",6))                  # 从结尾到word[6]间搜索
print (word.endwith("ld",6, 10))             # 在word[6:10]中搜索
print (word.endwith("ld",6, len(word)))    # 在word[6:11]中搜索 

1.6字符串的反转

# 循环输出反转的字符串
def reverse(s):
    out = ""
    li = list(s)
    for i in range(len(li), 0, -1):
        out += "".join(li[i-1])
return out


# 方法二
def reverse(s):
    li = list(s)
    li.reverse()
    s = "".join(li)
return s

1.7字符串的查找和替换

# find()函数
find(substring [, start [ ,end]])
# 在[start:end]间查找substring,若找到返回第1次出现的索引,否则返回-1

# rfind()参数与find()相同,不同的是前者从末尾开始查找子串

# 查找字符串
sentence = "this is a apple."
print (sentence.find("a"))                  # 8
print (sentence.rfind("a"))                 # 10
# replace()函数
replace(old, new [, max])
# 用new替换old,max表示替换次数。 返回一个新的字符串。

# 用法
sentence = "hello world, hello China"
print (sentence.replace("hello","hi"))            # hi world, hi China
print (sentence.replace("hello","hi", 1))        # hi world, hello China
print (sentence.replace("abc","hi"))              # hello world, hello China

PS: replace()先创建变量sentence的拷贝,然后在拷贝中替换字符串,并不会改变sentence的内容

1.8字符串与日期转换 

# strftime()
strftime(format[, tuple])  -> string
# format表示格式化日期的特殊字符
# tuple表示需要转换的时间,用元组储存。其中元素分别为年、月、日、分、秒
# 函数返回一个表示时间的字符串

字符串到时间的转换需要进行两次,使用time模板和datetime类,转换过程分为以下三步骤。

  • 调用函数strptime()把字符串转换为一个元组
strftime(format[, tuple])  -> string
  • 把表示时间的元组赋值给表示年、月、日的3个变量
  • 把表示年月日的三个变量传递给函数datetime(),进行第二次转换。
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
# 函数返回一个datetime类型的变量

 

# 时间转换过程
import time,datetime

# 时间到字符串的转换
print (time.strftime("%Y-%m-%d %X", time.localtime()))                # 2016-09-24 15:42:33

# 字符串到时间的转换
t = time.strptime("2016-09-24", "%Y-%m-%d")
y, m ,d = t[0:3]
print (datetime.datetime(y,m,d))                # 2016-09-24 00:00:00

 2.正则表达式

2.1简介

正则表达式用于搜索、替换和替换字符串。使用其编写一些逻辑验证非常方便。

正则表达式是用于文本匹配的工具,它在源字符串中查找与给定的正则表达式相匹配的部分。一个正则表达式是由字母、数字和特殊字符(括号、星号、问号等)组成。

符号描述符号描述
^表达式的开始字符。在[^m] 中例外      \b匹配单词的开始和结束
$表达式的结束字符\B匹配不是单词的开始和结束的位置     
\w匹配字母、数字、下划线.匹配任意字符,包括汉字
\W匹配不是字母、数字、下划线的字符[m]匹配单个字符串
\s匹配空白字符[m1m2...n]匹配多个字符串
\S匹配不是空白的字符[m-n]匹配m到n区间内的数字、字母
\d匹配数字[^m]匹配除m以外的字符串
\D匹配非数字的字符()对正则表达式进行分组,一对圆括号表示一组    
*重复0或N次{m}重复m次
+重复1或N次{m,n}该限定符的意思是至少有 m 个重复,至多到 n 个重复
?重复0或1次  
    

 

\d{3}-\d{8} | \d{4}-\d{7}
#  表示区号为3位的8位数电话号码或区号为4位的7位数电话号码

#  也有的在区号两侧加圆括号分隔
[\( ]?\d{3}[\]-?\d{8}|[\( ]?\d{4}[\]-]?\d{7}
# ()是正则表达式特殊字符  前要加\

# 对三位数字重复三次
(\d\d\d){2}
# \d\d\d{2}   相当于 \d\d\d\d


# 通常,正则表达式匹配最长字符串。可在限定符后加"?",获取最短匹配
a.*c
# 对从a到c的字符串最长匹配
a.*?c
#  对从a到c的字符串最短匹配
符号描述符号描述
*?匹配零次或多次,且匹配最短(?#...)正则表达式中的注释
+?匹配一次或多次,且匹配最短(?P<name>...)给分组命名,name表示分组的名称
??匹配一次或零次,且匹配最短(?P=name)使用名为name的分组
{m,n}?重复m次,且匹配最短  

2.2使用re模块处理正则表达式

Python的re模块具有正则表达式的功能。re模块提供了一些根据正则表达式进行查找、替换、分隔字符串的函数,这些函数使用正则表达式作为第一个参数。

函数描述
re.compile(pattern, flags=0)编译正则表达式,返回RegexObject对象,然后可以通过RegexObject对象调用match()和search()方法。第二个参数flags是匹配模式,例如,re.IGNORECASE=2,re.MULTILINE=8(忽略大小写,从新行开始搜索)等等。
re.search(pattern, string, flags=0)在字符串中查找,是否能匹配正则表达式。返回_sre.SRE_Match对象,如果不能匹配返回None。
re.match(pattern, string, flags=0)字符串的开头是否能匹配正则表达式。返回_sre.SRE_Match对象,如果不能匹配返回None
re.split(pattern, string, maxsplit=0)根据pattern分隔string,maxsplit表示最大分割数
re.findall(pattern, string, flags=0)找到 RE 匹配的所有子串,并把它们作为一个列表返回。这个匹配是从左到右有序地返回。如果无匹配,返回空列表。
re.finditer(pattern, string, flags=0)找到 RE 匹配的所有子串,并把它们作为一个迭代器返回。这个匹配是从左到右有序地返回。如果无匹配,返回空列表
re.sub(pattern, repl, string, count=0, flags=0)找到 RE 匹配的所有子串,并将其用一个不同的字符串替换。可选参数 count 是模式匹配後替换的最大次数;count 必须是非负整数。缺省值是 0 表示替换所有的匹配。如果无匹配,字符串将会无改变地返回。
re.subn(pattern, repl, string, count=0, flags=0)与re.sub方法作用一样,但返回的是包含新字符串和替换执行次数的两元组。
re.escape(string)对字符串中的非字母数字进行转义
re.purge()清空缓存中的正则表达式

正则表达式积累——常用:

1.  .*? 是一个固定的搭配,.和*代表可以匹配任意无限多个字符,加上?表示使用非贪婪模式进行匹配,也就是我们会尽可能短地做匹配。

2.  (.*?)代表一个分组,在这个正则表达式中我们匹配了五个分组,匹配完成后遍历item,item[0]就代表第一个(.*?)所指代的内容,item[1]就代表第二个(.*?)所指代的内容,以此类推。

3. re.S 标志代表在匹配时为点任意匹配模式,点 . 也可以代表换行符。用于( re.compile() )中的flags参数。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值