fengguozhen

导航

 

1.字符串的定义

在单引号、双引号、三引号内,由一串字符组成。

示例:name = "test"

2.字符串的操作

小技巧提示:可在pycharm 中CTRL + 鼠标左键点击str进入查看字符串的内置方法

1.将首写字母变成大写

test = "ceshi"
v= test.capitalize()
print(v)

2.将字母全部变为小写

test = "TEST"
v = test.casefold()
v1 = test.lower()
print(v, v1)

 3.将指定字符在规定的长度内居中显示,默认使用空格填充,可指定一个字符作为填充对象

test = "ceshi"
v = test.center(20,"*")
print(v)

4.统计一个子序列在一个字符串中出现的次数,可指定区间的开始结束位置

test = "ceshiceshiceshi"
v = test.count("ceshi",4,15)
print(v)

5.判断字符串是否以什么开始

test = "ceshiceshiceshi"
v = test.startswith("ceshi")
print(v)

6.判断字符串是否以什么结束

test = "ceshiceshiceshi"
v = test.endswith("ceshi")
print(v)

7.通过制表符进行断句,默认的长度为8

test = "ceshi\tceshi\tceshi\t\n123\t12345\t12345677"
v = test.expandtabs(20)
print(v)

8.查找子序列在所给的字符串中第一次出现的下标(可指定搜索区间),从左到右找,找不到返回-1

test = "ceshiceshiceshi1231234512345677"
v = test.find("ceshi")
print(v)

9.查找子序列在所给的字符串中最后一次出现的下标(可指定搜索区间),从左到右找,找不到返回-1

test = "ceshiceshiceshi123123"
v = test.rfind("ces")
print(v)

10.查找子序列在所给的字符串中第一次出现的下标(可指定搜索区间),从左到右找,找不到报错

test = "ceshiceshiceshi123123"
v = test.index("cesddd")
print(v)

 

11.查找子序列在所给的字符串中最后一次出现的下标(可指定搜索区间),从左到右找,找不到报错

test = "ceshiceshiceshi123123"
v = test.rindex("cesddd")
print(v)

 12.字符串格式化

# test = "我是一个{}的人,今年{}岁,喜欢{}"
# v = test.format("活泼",10,"打篮球")
# print(v)

# test = "我是一个{0}的人,今年{1}岁,喜欢{2}"
# v = test.format("活泼",10,"打篮球")
# print(v)

test = "我是一个{character}的人,今年{age}岁,喜欢{hobby}"
v = test.format(character="活泼",age=10,hobby="打篮球")
print(v)

test = "我是一个{character}的人,今年{age}岁,喜欢{hobby}"v = test.format_map({"character": "活泼", "age": 10, "hobby": "打篮球"})
print(v)

posted on 2021-03-14 13:00  fengguozhen  阅读(73)  评论(0)    收藏  举报