python字符串操作详析
作者:Silva72
这篇文章主要介绍了python字符串操作,字符串是不可变类型可以重新赋值,但不可以索引改变其中一个值,只能拼接字符串建立新变量,下面来了解具体内容吧,需要的小伙伴可以参考一下
字符串是不可变类型,可以重新赋值,但不可以索引改变其中一个值,只能拼接字符串建立新变量


索引和切片
索引:越界会报错切片:
越界会自动修改
不包含右端索引
需重小到大的写,否则返回空字符串
motto = '积善有家,必有余庆。' # 索引 print(motto[0]) # print(motto[10]) 报错 # 切片 不包含右侧 从小到大 print(motto[0:9]) print(motto[0:10]) print(motto[0:100]) print(motto[0:]) print(motto[-10:]) print(motto[-100:]) print(motto[-5:-1]) print(motto[0:10:2]) print(motto[:5]) print(motto[3:2]) # 若大到小,则返回'' print(motto[2:3])
一、5种字符串检索方法
s = "ILovePython"
# 1. str.count('',起点,终点)
print(s.count('o', 1, 5))
print(s.count('o'))
# 2. str.find('',起点,终点) 找不到返回-1
print(s.find('o',3))
print(s.find('o',3,5))
print(s.find('o'))
# 3. str.index('',起点,终点) 找不到则报错
print(s.index('o'))
print(s.index('Py'))
# 4. str.startswith('',起点,终点)
print(s.startswith("IL"))
print(s.startswith("L"))
# 5. str.endswith('',起点,终点)
print(s.endswith("on"))
print(s.endswith("n"))
print(s.endswith("e"))1 2 9 -1 2 2 5 True False True True False
二、join字符串拼接方法 [列表/元组 --> 字符串]
将列表元组,拼接成字符串
# join()函数
list_val = ['www', 'baidu', 'com']
str_val = '.'.join(list_val)
print(str_val)
tuple = ('Users', 'andy', 'code')
str_val = '/'.join(tuple)
print(str_val)三、3种字符串分割方法 [字符串 --> 列表/元组]
# 1. split('',分割次数) 默认从空格 \n \r \t切掉
s = "我 爱\t你\nPy thon"
print(s.split())
s1 = "python我爱你Python"
print(s1.split("y"))
s2 = "python我爱你Python"
print(s1.split("y", 1))
# 2. splitlines() 默认从换行符rt切掉
s = "我 爱\t你\nPy thon"
print(s.splitlines())
# 3. partition('') 不切掉 分成3元素元组
s = "我爱你Python"
print(s.partition('爱'))['我', '爱', '你', 'Py', 'thon']
['p', 'thon我爱你P', 'thon']
['p', 'thon我爱你Python']
['我 爱\t你', 'Py thon']
('我', '爱', '你Python')split()和splitlines()默认情况下的对比:

split()和partition()对比:split()切掉后变列表,partition()不切掉变元组
四、5种大小写转换方法
string_val = 'I love Python' print(string_val.upper()) print(string_val.lower()) print(string_val.title()) # 每个单词第一个字母变大写 print(string_val.capitalize()) # 仅第一个字母变大写 print(string_val.swapcase())
I LOVE PYTHON i love python I Love Python I love python i LOVE pYTHON
五、3种字符串修剪方法
默认首尾的空格和换行符\t\r进行修剪
可用参数设定首尾的其他符号进行修剪
lstrip() 只删首rstrip() 只删尾
s = " ILovepython"
print(s)
print(s.strip())
print(s.strip(' I'))
print(s.strip('n'))
s1 = "00000003210Runoob0123000000"
print(s1.strip('0'))
print(s1.lstrip('0'))
print(s1.rstrip('0'))ILovepython ILovepython Lovepython 3210Runoob0123 3210Runoob0123000000 00000003210Runoob0123
到此这篇关于python字符串操作的文章就介绍到这了,更多相关python字符串操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
