Python - 字符串常用函数详解

简介: Python - 字符串常用函数详解

str.index(sub, start=None, end=None)


作用:查看sub是否在字符串中,在的话返回索引,且只返回第一次匹配到的索引;若找不到则报错;可以指定统计的范围,[start,end) 左闭区间右开区间

str = "helloworldhhh"
print(str.index("h"))
print(str.index("hhh"))
# print(str.index("test")) 直接报语法错误:ValueError: substring not found


执行结果

0

10

 

str.find(sub, start=None, end=None)


作用:和index()一样,只是找不到不会报错,而是返回-1

str = "helloworldhhh"
print(str.find("h"))
print(str.find("hhh"))
print(str.find("test"))

执行结果

0

10

-1

 

str.count( sub, start=None, end=None)


作用:统计子字符串的数量;可以指定统计的范围,[start,end) 左闭区间右开区间

str = "hello world !!! hhh"
print(str.count(" "))
print(str.count(" ", 5, 10))

执行结果

3

1

 

 

str.split(str="", num=string.count(str))


作用:将字符串按照str分割成列表,如果参数 num 有指定值,则分隔 num+1 个子字符串

str = "hello world !!! hhh"
print(str.split(" "))
print(str.split(" ", 1))

执行结果

['hello', 'world', '!!!', 'hhh']
['hello', 'world !!! hhh']

str.strip(chars = " ")


作用:移除字符串头尾指定的字符序列chars,默认为空格


str.lstrip(chars = " ")


作用:移除字符串头部指定的字符序列chars,默认为空格


str.rstrip(chars = " ")


作用:移除字符串尾部指定的字符序列chars,默认为空格


str = "   hello  every  "
print("1", str.strip(), "1")
print(str.lstrip(), "1")
print("1", str.rstrip())
str = "!!! cool !!!"
print(str.strip("!"))


执行结果

1 hello  every 1
hello  every   1
1    hello  every
 cool 


str.replace(old,new,count= -1)


作用:把字符串中的 old(旧字符串) 替换成 new(新字符串),count代表最多替换多少次,默认-1代表全部替换

str = "hello world !!! hhh"
print(str.replace(" ", "-"))
print(str.replace(" ", "-", 1))

执行结果

hello-world-!!!-hhh
hello-world !!! hhh


str.join(sequence)


作用:将序列中的元素以指定的字符连接生成一个新的字符串

lists = ["1", "2", "3"]
tuples = ("1", "2", "3")
print("".join(lists))
print("".join(tuples))
print("-".join(lists))

执行结果

123
123
1-2-3


知识点

  • "".join(lists) 这是最常见的将列表、元组转成字符串的写法
  • 列表里面只能存放字符串元素,有其他类型的元素会报错
  • 元组也能传进去

 

str.upper()


作用:将字符串都变成大写字母


str.lower()


作用:将字符串都变成小写字母

str = "hello world !!! hhh"
print(str.upper())
print(str.lower())

执行结果

HELLO WORLD !!! HHH

hello world !!! hhh

 

str.startswith(prefix, start=None, end=None)


作用:检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False;可以指定统计的范围,[start,end) 左闭区间右开区间


str.endswith(self, suffix, start=None, end=None)


作用:相反这是结尾

str = "hello world !!! hhh"
print(str.startswith("h"))
print(str.startswith("hh"))
print(str.endswith("h"))
print(str.endswith("hhhh"))

执行结果

True
False
True
False


str.isdigit()


作用:检查字符串是否只由数字组成

str = "123134123"
print(str.isdigit())

执行结果

true

 

str.isalpha()


作用:检查字符串是否只由字母组成

str = "abc"


print(str.isalpha())

执行结果

true

 

str.splitlines([keepends])


作用:将字符串按照行 ('\r', '\r\n', \n') 分隔

str = """
123
456
789
"""
print(str.splitlines())
with open("./file1.txt", encoding="utf-8") as f:
    lists = f.read().splitlines()
    print(lists)

执行结果

['', '123', '456', '789']
['name: Jack   ;    salary:  12000', ' name :Mike ; salary:  12300', 'name: Luk ;   salary:  10030', '  name :Tim ;  salary:   9000', 'name: John ;    salary:  12000', 'name: Lisa ;    salary:   11000']
相关文章
|
15天前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
72 1
|
15天前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
105 1
|
15天前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
78 0
|
26天前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
236 101
|
1月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
216 100
|
1月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
171 99
|
1月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
300 99
|
1月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
151 98
|
1月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
1月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧

热门文章

最新文章

推荐镜像

更多