Python基础学习之字符串操作

Python基础学习之字符串操作

字符串是编程中最常遇到的类型,所以掌握好字符串的常用操作方法,非常的必要!

1. 字符串的切片 []

字符串的切片是最常见的字符串操作,必须要掌握;

#切片语法
str_1='123456789'
print(str_1[1:5])     # 输出为:2345
print(str_1[::])   #全部元素,输出为:123456789
print(str_1[1:8:2])   #输出为:2468
print(str_1[::-1])    #可以实现倒序,输出为:987654321
print(str_1[-5:-2])   #输出为:567

2. 字符串的统计值 len(), count()

  1. len() 统计字符串的长度
str_1='123456789'
# 获取长度
len(str_1)   #结果输出为:9
  1. count() 统计指定字符的个数
a='hello world'
print(a.count('l'))     # 输出结果为:3

3. 查找字符串 find(),index()

查找字符串的方法有:index(), find(), rfind(), lfind();
index() 与 find() 的功能相同,不同点为:find()查找失败会返回-1,不会影响程序运行。一般用返回值来做判断,例如:find!=-1或者find>-1来作为判断条件。

#查找字符串
print('hello'.index('l'))    # 输出2
print('hello'.find('l'))     # 输出2
print('hello'.rfind('l'))    # 输出3
print('hello'.rfind('a'))    # 输出 -1
print('hello'.rfind('llo'))   # 输出2

4. 字符串的替换 replace()

print('hello word'.replace('word', 'world'))   #输出 hello world

5. 连接字符串 + & join()

  1. 加好运算符可以连接字符串,但是 + 号运算符,比较浪费内存;
a='I have an apple!'
b='I have a pen!'
c=a+b
print(c)
  1. 将列表连接成字符串;
list1=['monday','tuesday','wednesday','thursday']
print('++'.join(list1))  #输出:monday++tuesday++wednesday++thursday

6. 分割字符串 split(),splitlines(),partition()

  1. split() 按照指定的字符进行分割;
'hello world'.split(' ')   #输出:['hello', 'world']
'hello world'.split('w')   #输出:['hello ', 'orld']
  1. partition() 按照指定的字符进行分割,分割后返回值为元组;
s="我是祖国的花朵!"
res = s.partition('祖国')
print(res)   # 输出元组:('我是', '祖国', '的花朵!')
  1. splitlines() 按照行分隔符进行分割,返回值为列表;
st='''我是祖国的花朵,
我也是接班人;
'''
b=st.splitlines()
print(b)  # 输出结果为:['我是祖国的花朵,', '我也是接班人;']

7. 包含运算 in & not in

a='hello world'
print('hello' in a)   # 输出:True
print('hello' not in a)   #输出:False

8. 字符串大小写转换 upper(),lower(),title(),capitalize()

'hello world'.capitalize()   # 第一个单词首字母大写,输出:'Hello world'
'hello world'.upper()     #全部大写,输出:'HELLO WORLD'
'HELLO world'.lower()     # 全部小写,输出:'hello world'
'hello world'.title()   #每个单词的首字母大写,输出:'Hello World'

9. 字符串的判断 islower(),endswith()等

'hello world'.startswith('e')   # 输出: False
'hello world'.endswith('d')   # 输出: True
'a'.isalpha()  # 输出: False
'23'.isdigit()  # 输出: True
'23'.isalnum()  # 输出: True
'hello world'.isspace()  # 输出: False
'hello world'.islower()   # 字母是否全是小写 
'hello world'.isupper()   # 字母是否是大写 
'hello world'.istitle()   # 首字母是否大写

10. 字符串与列表之间的转换 split(), join()

  1. 字符串转化为列表;实际上就是字符串的分割; split()
'hello world'.split(' ')   #输出:['hello', 'world']
'hello world'.split('w')   #输出:['hello ', 'orld']
  1. 列表转化成字符串;实际上是字符串的合并;
a=['monday','tuesday','wednesday','thursday']
print('++'.join(a))   #输出:monday++tuesday++wednesday++thursday

11. 字符串的对齐与居中 center(),ljust(),rjust()

# 对齐  三种剧中方式的参数均为:(width,fillchar)
str_1.ljust(10)    # 让字符串以制定长度显示,不足则以空格补齐;
str_1.rjust(10,'#')    ## 让字符串以制定长度显示,右对齐
str_1.center(20,'#')    #让字符串以制定长度显示,居中

12. 字符串的运算符 +,*,==,!=,<,>,=

  1. 加法运算,合并字符串;
  2. 乘法运算,自定字符串重复多次
  3. == 运算,返回布尔类型
  4. != 运算
  5. 比较运算(<,>,=),比较字符串的编码值,返回布尔类型;

13. 字符与编码的转换 ord(),chr(),encode(),decode()

# 字符与编码的转换
ord('这')   #获得字符的编码值
chr(12456)   #获得编码的字符

# GBK,UTF-8编码
print('你'.encode('GBK'))    #十六进制:b'\xc4\xe3' 十进制:50403  二进制:11000100 11100011,一个字符占两个字节
print(b'\xc4\xe3'.decode('GBK')) # 输出:你!


# UTF-8编码
print('你'.encode('utf8'))    #十六进制:b'\xe4\xbd\xa0' 十进制:14990752  二进制:11100100 10111101 10100000,一个字符占三个字节
print(b'\xe4\xbd\xa0'.decode('utf8')) # 输出:你!

14. 两种字符串占位符 (% & format{})

  1. %占位符
# %占位符

print('大家好,我是%s,我今天挣了%d块钱!' %('张凯',5))
# 输出:大家好,我是张凯,我今天挣了5块钱!
print('大家好,我是%s,我今天挣了%4d块钱!' %('张凯',5))
# 输出:大家好,我是张凯,我今天挣了   5块钱!
print('大家好,我是%s,我今天挣了%-4d块钱!' %('张凯',5))
# 输出:大家好,我是张凯,我今天挣了5   块钱!
print('大家好,我是%s,我今天挣了%04d块钱!' %('张凯',5))
# 输出:大家好,我是张凯,我今天挣了0005块钱!
print('大家好,我是%s,我今天挣了%.2f块钱!' %('张凯',5.2548))   #四舍五入保留两位小数
# 输出:大家好,我是张凯,我今天挣了5.25块钱!

print('大家好,我是%s,我今天挣了%x块钱!' %('张凯',10))
# 输出:大家好,我是张凯,我今天挣了a块钱!
print('大家好,我是%s,我今天挣了%X块钱!' %('张凯',10)) 
# 输出:大家好,我是张凯,我今天挣了A块钱!
  1. format 占位符
# format 占位符
# {}内什么都不填,按顺序进行;
x='大家好,我是{},我今天赚了{}块钱'.format('张凯',19)
print(x) 
# 输出:大家好,我是张凯,我今天赚了19块钱
# {}内填写数字,可控制顺序;
x='大家好,我是{1},我今天赚了{0}块钱'.format('张凯',19)
print(x)  
# 输出:大家好,我是19,我今天赚了张凯块钱
# {}内填写变量;
x='大家好,我是{name},我今天赚了{money}块钱'.format(name='张凯',money=19)
print(x)  
# 输出:大家好,我是张凯,我今天赚了19块钱

# *可以将list 拆包
list_for=['张凯',19]
x='大家好,我是{},我今天赚了{}块钱'.format(*list_for)
print(x)  
# 输出:大家好,我是张凯,我今天赚了19块钱

# *可以将dict 按key value 匹配拆包
dic_for={
    
    'name':'张凯','money':19}
x='大家好,我是{name},我今天赚了{money}块钱'.format(**dic_for)
print(x)  # 输出:大家好,我是张凯,我今天赚了19块钱

猜你喜欢

转载自blog.csdn.net/weixin_47139649/article/details/108646750