代码运行 python 版本 3.7
index() 获取子串在字符串中出现的位置索引值
lang = 'aaa1113234'
lang.index('a')
# 0
lang.index('1')
# 3
lang.index('23')
# 7
使用索引获取单字符
索引0为第一字符。索引可为负数,表示从尾部(右侧)起始
lang = 'python'
lang1 = '老陆编程测试中文'
lang[3]
# h
lang1[3]
# 程
lang[-1]
# n
lang1[-1]
# 文
使用切片获取子串
获取子串包括首索引字符,不包括尾索引字符
lang[1:4]
# yth
lang[1:]
# ython
lang[:3]
# pyt
lang[-2:]
# on 注意此处尾索引不能为0,否则得到空字符串''
lang[-4:-2]
# th
lang[:-4]
# py
lang[:]
# python
反转字符串
中文也有效
lang1 = '老陆编程测试中文'
lang1[::-1]
# 文中试测程编陆老
len()方法获取字符串长度
len(lang)
# 6
len(lang1)
# 8
in 操作符判断子串是否在字符串中
'p' in lang
# True
'ab' in lang
# False
'测试' in lang1
# True
max() 和 min() 获取字符串中编码最大和最小的字符
max(lang)
# y
min(lang)
# h
max(lang1)
# 陆
min(lang1)
# 中
操作符 * 对字符串进行重复
lang * 2
# pythonpython
lang1 * 2
# 老陆编程测试中文老陆编程测试中文
使用比较运算符(>、<、<=、>=、!=、==)比较字符串
因为是编码比较,这种比较用处不大
lang > lang1
# False
'F'>'f'
# False
chr() 和 ord() 在字符和编码间转化
ord('测')
# 27979
chr(27979)
# 测
str() 将其他数据类型转化为字符串
num = 3.14
str(num)
# 3.14
capitalize() 方法将字符串第一字符变大写,其他变小写
全角英文也有效
lang2 = 'p测试K pYthon'
lang2.capitalize()
# P测试k python
lang.capitalize()
# Python
upper()、lower() 函数对字符串中字符转大写和小写
全角英文也有效,全角英文转换时返回对于的全角大小写
lang2 = 'p测试K pYthon'
lang2.upper()
# P测试K PYTHON
lang2.lower()
# p测试k python
swapcase() 对字符串中所有字符进行大小写互换
大写变小写,小写变大写,中文无效
lang2 = 'p测试K pYthon'
# P测试k PyTHON
strip()、lstrip() 和 rstrip() 去掉首尾空格、做空格、右空格
' python '.strip()
# 'python'
' python '.lstrip()
# 'python '
' python '.strip()
# ' python'
split() 方法按指定字符串分割,返回 list
lang2 = 'p测试K pYthon'
lang2.split('K p')
# ['p测试', 'Ython']
jion() 方法链接字符串数组
a = 'hello world'.split()
'|-|'.join(a)
# hello|-|world
find() 方法判断一个字符串中是否包含子串
三个参数,第一个必须,指定需要搜索的子串,第二、三参数指定搜索起始位置和终止位置,搜索得到则返回索引值,得不到则返回-1
'hello world'.find('llo')
# 2
'hello world'.find('lloe')
# -1
endswith() 和 startswith() 方法判断一个字符串是否以某个字符串结尾、开头,参数和find()一致
'hello'.startswith('he')
# True
'hello'.endswith('lo')
# True
'hello'.endswith('le')
# False
count() 方法获取某个子串在字符串中出现的次数
lang3 = '老陆编程测试字符串统计测试编程'
lang3.count('程')
# 2
lang3.count('测试')
# 2
lang3.count('老陆')
# 1
isupper()、islower()判断字符串中字符是否都是大、小写
如果字符串中有中文,中文会被忽略只判断字符串中的英文,如果字符串中全是中文则这两个方法都返回False,全角英文也可正常判断
'Y测试K'.isupper()
# True
'Y测试k'.isupper()
# False
replace(old,new) 用字符串new替换字符串中的子串old
'这是测试old子串'.replace('old', 'new')
# 这是测试new子串