python 常用数据类型(二)-- 字符串

本贴最后更新于 770 天前,其中的信息可能已经物是人非

一、字符串的特性

  1. 字符串不可修改
  2. 字符串是有序的
  3. 字符串是可迭代的

# 二、字符串的创建

  1. test_str='张三'
  2. test_str='''张三'''
  3. test_str="""张三"""
  4. 创建空字符串:test_str=''

三、字符串的相关操作

1、通过索引访问字符串

语法:test_str[索引值]

  1. 正序索引:索引值从0开始(字符串从左往右每个字符占一个索引,依次为0,1,2,3,4……)
  2. 倒序索引:索引值从-1开始(字符串从右往左眉哥字符占一个索引,依次为-1,-2,-3,-4……)

2、字符串切片

语法:test_str[起始索引值:结束索引值:步长]

  1. 正序切片:使用正序索引,步长为正数 test_str[1:3:1],输出的结果是正序的字符串
  2. 倒序切片:使用倒序索引,步长为负数 test_str[-1:-3:-2],输出的结果是倒序的字符串

注意:

test_str = '123456'
res1 = test_str[0:3:2]		# 输出为:13
res2 = test_str[-1:-3:-2]	# 输出为:6
res3 = test_str[::-1]		# 输出为:654321

3、字符串运算

  1. 字符串拼接( + )
  2. 字符串重复输出( * )
test_str1 = '123456'
test_str2 = 'abc'
print(test_str1 + test_str2)	# 输出为:123456abc
print(test_str1 * 2)		# 输出为:123456123456

4、字符串转义

  1. \ 转义,需要对字符串中的每个 \ 进行转义处理
  2. r 转义,对整个字符串进行转义
print('123\t456\t789')	# 输出为:123	456	789
print('123\\t456\t789')	# 输出为:123\t456	789
print(r'123\t456\t789')		# 输出为:123\t456\t789

5、字符串常用方法

1. 单词大小写相关

所有字符转大写:test_str.upper()

所有字符转小写:test_str.lower()

将字符串大小写互换:test_str.swapcase()

将字符串首字母大写:test_str.capitalize()

将字符串中每个单词的首字母大写:test_str.title()

2. 统计相关

计算某个字符在字符串中出现的次数:test_str.count(要统计的字符,开始索引值,结束索引值)

统计字符串的长度:len(test_str)

查找某个字符在字符串中第一次出现的索引值:test_str.find('t')

查找某个字符在字符串中最后一次出现的索引值:test_str.rfind('t')

3. 判断相关

判断字符串是否都是大写:test_str.isupper()

判断字符串是否都是小写:test_str.islower()

判断字符串是否是空格:test_str.isspace()

判断字符串是否都是数字:test_str.isdigit()

判断字符串是否有字母或数字:test_str.isalnum()

判断字符串是否以指定字符开头:test_str.startwith('t')

判断字符串是否以指定字符结尾:test_str.endwith('t')

4. 字符串拆分、连接、替换

字符串拆分: test_str.split(拆分标识,maxsplit=-1)

注意:
a) 不写拆分标识,默认按空格拆分
b) maxsplit表示拆分次数,不限制拆分次数配-1
c) 拆分结果以list形式返回

test_str = '12131415'
res = test_str.split('1')
print(res)		# 输出为:['', '2', '3', '4', '5']

字符串连接:'_'.join(test_str)

注意:连接的结果仍是字符串

test_str = 'abcde'
res = '_'.join(test_str)
print(res)		# 输出为:a_b_c_d_e

字符串替换: test_str.replace(old,new,count)

注意:
a) old:需要被替换的字符
b) new:需要放进去的字符
c) count:替换次数,默认全部替换

test_str = '012131415'
res = test_str.replace('1','_')
print(res)		# 输出为:0_2_3_4_5

5. 字符串成员运算

判断字符在字符串中存在:in

判断字符在字符串中不存在:not in

注意:成员运算返回的结果是布尔值

test_str = '012131415'
print('x' in test_str)		# 输出为:False
print('x' not in test_str)	# 输出为:True

6. 字符串格式化

1)占位符

%s:字符占位符

%d:数值占位符

%f:浮点数占位符

%.2f:指定小数位数的浮点数占位符

缺点:需要提前预判传入值的数据类型,放置对应的占位符

print('姓名:%s' % ('张三'))
print('年龄:%d' % (100))
print('工资:%f' % (10000 / 3))
print('省略后工资:%.2f' % (10000 / 3))
# 输出为:
# 姓名:张三
# 年龄:100
# 工资:3333.333333
# 省略后工资:3333.33

2)formate

优点:支持所有数据类型的传入

res1 = "this is a {}".format("phone")	#按顺序取值
res2 = "this is a {0},that is a {1}".format("phone", "tel")	#按索引取值
res3 = "this is a {x1},that is a {x2}".format(x1="phone", x2="tel")	#按关键字取值

3)f

提前定义好变量,在字符串中以{变量名}的形式占位,字符串最前面标f

x1 = "phone"
x2 = "tel"
aa = f"this is a {x1},that is a {x2}"
print(aa)		# 输出为:this is a phone,that is a tel
回帖
请输入回帖内容 ...