本文对python常用字符串操作进行介绍,包括字符串匹配、截取、替换
操作环境:python3.6
相关函数介绍:
函数 | 说明 |
string.find(str, beg=0, end=len(string)) | 检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1 |
string.index(str, beg=0, end=len(string)) | 和find使用方式一样,若匹配为空报异常 |
string.strip([obj]) | 删除 string 字符串开头和末尾的空格. |
string.replace(str1, str2, num=string.count(str1)) | 把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次. |
string.split(str="", num=string.count(str)) | 以 str 为分隔符切片 string,如果 num 有指定值,则仅分隔 num+ 个子字符串 |
re.match(pattern, string, flags=0) | re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。 |
代码如下:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
import re
import os
str1=" hello world python! "
#过滤空格
str2=str1.strip(" ")
print(f"....{str2}....")
#匹配hello是否存在
print("hello位置:"+str(str2.find("hello")))
if str2.find("hello") !=-1:
print("字符存在")
#判断字符是否已hello开头
#正则玩法很多,此处就不多做介绍
if re.match(r"^hello",str2):
print("字符是hello开头")
#以空格对str2进行切割
str3=str2.split(" ")
for i in str3:
print ("序号:%s 值:%s" % (str3.index(i) + 1, i))
#对world进行替换
print(str2.replace("world", "世界"))
结果如下:
....hello world python!....
hello位置:0
字符存在
字符是hello开头
序号:1 值:hello
序号:2 值:world
序号:3 值:python!
hello 世界 python!
官网是最好的导师:https://www.python.org/
上一篇:python之json文件操作