str(数据):所有的数据都可以转换成字符串;转换的时候是在数据的打印值外面加引号。
num = 123
# srr(sum) - # '123'
num2 = 1.23
# str(num2) - # '1.23'
list1 = [10,20,30]
print(list1) # [10, 20, 30]
# str(list1) - # '[10, 20, 30]'
list2 = ["abc",10,20]
print(list2)
# str(list2) - # "['abc', 10, 20]"
list3 = ["abc",10,20,'a']
print(list3)
# str(list3) - # "['abc', 10, 20, 'a']"
dict1 = {'a':10,'b':20}
print(dict1)
# str(dict1) - # "{'a': 10, 'b': 20}"
str1 = str(dict1)
for x in str1:
print(x)
1.3 eval
eval(字符串):获取指定字符串引号中的内容(去掉字符串的引号)。
注意:这儿的字符串去掉引号后必须是一个合法的表达式。
1.3.1 去掉引号以后是合法数据result = eval('100') # 100
print(result,result * 2,result + 10) # 100 200 110
# result = eval('abc') # 报错
result = eval('"abc"') # 'abc'
print(result,len(result))
result = eval('[10,20,30]') # [10, 20, 30]
result.append(100)
print(result) # [10, 20, 30, 100]
1.3.2 去掉引号后是合法的表达式
result = eval('100 + 200') # 100 + 200
print(result) # 300
abc = 10
result = eval('abc + 100') # abc + 100
print(result) # 110
nums = [10,20,30]
eval('nums.append(100)') # nums.append(100)
print(nums) # [10, 20, 30, 100]
2. 字符串相关方法
2.1 join
字符串.join(序列):将序列中的元素用指定的字符串连接成一个新的字符串(序列中的元素必须全部是字符串)。
list1 = ['hello','world!','您好','世界'] result = ''.join(list1) print(result) # 'helloworld!您好世界' result = ','.join(list1) print(result) # 'hello,world!,您好,世界' result = '123'.join(list1) print(result) # 'hello123world!123您好123世界' str1 = 'hello' result = ' '.join(str1) print(result) # 'h e l l o'2.1.1 练习
练习1::将nums中的元素拼接成一个数字,102030452。
nums = [10, 20,30, 4, 52] result = ''.join([str(x) for x in nums]) print(int(result)) # 102030452
练习2:将nums中所有的个位数拼接成一个数字字符串, ‘09042’。
nums = [10, 29, 30, 4, 52] result = ''.join(str(x % 10) for x in nums) print(result,type(result)) # '09042'
练习3:将list1中所有的数字用’+'连接,并且计算他们的和: ‘19+1.23+8+22.2=50.43’。
list1 = [19, 'abc', True, 1.23, 8, 22.2, '环境'] result = '+'.join(str(x) for x in list1 if type(x) in (int,float)) print(result,eval(result),sep='=') # 19+1.23+8+22.2=50.432.2 split 2.2.1 字符串1.split(字符串2)
将字符串1中所有的字符串2作为切割点对字符串1进行切割,返回一个包含多个字符串的列表。
str1 = 'abc123hello123你好123python'
result = str1.split('123')
print(result) # ['abc', 'hello', '你好', 'python']
2.2.2 字符串1.split(字符串2,N)
将字符串1中前N个字符串2作为切割点对字符串1进行切割,返回一个包含多个字符串的列表。
str1 = 'abc123hello123你好123python'
print(str1.split('123',2)) # ['abc', 'hello', '你好123python']
注意:如果切割点在字符串开头、或者字符串结尾、或者连续出现多个切割点,都会产生空串。
str1 = '123abc123hello123123你好123python123'
print(str1.split('123')) # ['', 'abc', 'hello', '', '你好', 'python', '']
2.3 replace
2.3.1 字符串1.replace(字符串2,字符串3)
将字符串1中所有的字符串2都替换成字符串3。
tr1 = 'how are you? Im fine, Thank you! you see,one dey day!'
# you -> me
result = str1.replace('you','me')
print(result) # 'how are me? Im fine, Thank me! me see,one dey day!!'
2.3.2 字符串1.replace(字符串2,字符串3,N)
将字符串1中前N字符串2都替换成字符串3。
result = str1.replace('you','me',1)
print(result) # how are me? Im fine, Thank you! you see,one dey day!
2.4 strip
字符串.strip():去掉字符串前后的空白字符。
str1 = ' t n good good study n '
print(str1)
result = str1.strip()
print(result)
str2 = 'good good study'
result = str2.strip('/')
print(result) # 'good good study'
2.5 count
字符串1.count(字符串2):统计字符串1中字符串2出现的次数。
str1 = 'how are you? Im fine, Thank you! you see,one dey day!'
print(str1.count('you')) # 3
2.6 maketrans、translate
2.6.1 maketrans(字符串1,字符串2)
通过字符串1和字符串2创建替换对应关系表。
table = str.maketrans('abc','123') # a-1,b-2,c-3
print(table) # {97: 49, 98: 50, 99: 51}
2.6.2 字符串.translate(对应关系)
按照对应关系表将字符串中的字符进行替换。
str1 = 'aadfbbmnccee' result = str1.translate(table) print(result) # 11df22mn33ee2.7 center、 ljust、rjust、zfill 2.7.1 字符串.center(长度,字符)
将指定字符串编程指定长度,不够的用指定字符填充;原字符串放中间。
2.7.2 字符串.ljust(长度,字符)将指定字符串编程指定长度,不够的用指定字符填充;原字符串放左边。
2.7.3 字符串.rjust(长度,字符)将指定字符串编程指定长度,不够的用指定字符填充;原字符串放右边,
字符串.zfill(长度) == 字符串.rjust(长度,‘0’)
# abcxxxx、xxxxabc、xxabcxx str1 = 'abc' print(str1.center(7,'x')) # 'xxabcxx' print(str1.ljust(7,'x')) # 'abcxxxx' print(str1.rjust(7,'x')) # 'xxxxabc' print(str1.center(2,'x')) # 'abc' num = '123' print(num.zfill(5)) # '00123'2.8 find、index
1)字符串1.find(字符串2):获取字符串2在字符串1中第一次出现的位置,如果字符串不存在返回-1;
2)字符串1.index(字符串2):获取字符串2在字符串1中第一次出现的位置,如果字符串2不存在报;错!
3)字符串1.rfind(字符串2):从后往前,获取字符串2在字符串1中最后一次出现的位置;
4)字符串1.rindex(字符串2) 。
str1 = 'how are you? Im fine, Thank you!'
print(str1.find('you')) # 8
print(str1.index('you')) # 8
print(str1.find('youu')) # -1
# print(str1.index('youu')) # 报错!ValueError: substring not found
print(str1.rfind('you')) # 28
print(str1.rindex('you')) # 28
2.9 isdigit、isnumeric
判断是否是纯数字字符串。
1)字符串.isdigit:判断字符串中的元素是否全是数字字符(0~9);
2)字符串.isnumeric:判断字符串中的元素是否全是具有数字意义的字符。
str1 = '1234'
print(str1.isdigit()) # True
print(str1.isnumeric()) # True
str1 = '123一二百肆ⅠⅡ壹'
print(str1.isdigit()) # False
print(str1.isnumeric()) # True
print('k'.islower(),'a' <= 'k' <= 'z') # True True
print('M'.isupper()) # True
print('jdbGHJGU'.lower()) # jdbghjgu
print('hjfdhjGHGJDGF'.upper()) # HJFDHJGHGJDGF
3. 格式字符串
# name = input('请输入姓名:')
name = '小明'
# age = int(input('请输入年龄:'))
age = 18
# 问题:写代码的时候可能会出现一个字符串中的部分内容无法确定
# xxx今年xx岁!
# 方法1:字符串拼接
str1 = name + '今年' + str(age) + '岁!'
print(str1)
# 方法2:使用格式占位符
str1 = '%s今年%d岁!' %(name,age)
print(str1)
# 方法3:使用f-string
str1 = f'{name}今年{age}岁!'
print(str1)
3.1 格式占位符创建字符串
3.1.1 语法
包含格式占位符的字符串 % (数据1,数据2,数据3,…)。
3.1.2 注意后面括号中的数据必须和前面字符串中的占位符一一对应。
3.1.3 常用的格式占位符1)%s:字符串占位符,可以对应任何类型的数据;
2)%d:整数占位符,可以对应任何数字;
3)%f:浮点数占位符,可以对应任何数字;
4)%.nf:保留n位小数。
# xxx今年xx岁,月薪xx元 str1 = '%s今年%d岁,月薪:%.2f元!' %(name,age,10000-800) print(str1) # '小明今年18岁,月薪:9200.00元!' price = 32.255 str2 = '价格:%s' % price print(str2) # 价格:32.255 str2 = '价格:%d' % price print(str2) # 价格:32 str2 = '价格:%f' % price print(str2) # 价格:32.255000 str2 = '价格:%.2f' % price print(str2) # 价格:32.263.2 f-string 3.2.1 语法
在字符串最前面加f,就可以在字符串中通过’{表达式}'来提供字符串中变化的部分。
3.2.2 基本用法name = '小明'
str1 = '{name}'
print(str1) # '{name}'
str1 = f'{name}'
print(str1) # '小明'
str1 = f'{name * 2}'
print(str1) # '小明小明'
str1 = f'{name[1] * 3}'
print(str1) # '明明明'
str1 = f'{name}=={age + 10}'
print(str1) # '小明==28'
score = [90,80,77]
str1 = f'{name}三门学科的分数:{str(score)[1:-1]}'
print(str1) # '小明三门学科的分数:90, 80, 77'
3.2.3 加参数
加参数:{表达式:参数}。
1)控制小数位数的参数:{表达式:.nf}。
money = 16543
str1 = f'年薪:{money * 13:.2f}元'
print(str1) # '年薪:215059.00元'
2)显示百分比:{表达式:.n%}。
rate = 0.87
str1 = f'班级及格率:{rate:.2%}'
print(str1) # '班级及格率:87.00%'
3)逗号显示金额:{表达式:,}。
# 1,000
# 10,000
# 55,645,649,854
money = 1654356
str1 = f'年薪:{money * 13:,}元'
print(str1) # '年薪:21,506,628元'
money = 1654356
str1 = f'年薪:{money * 13:,.2f}元'
print(str1) # '年薪:21,506,628.00元'
4)修改填充内容的长度:{表达式:字符>长度}、{表达式:字符<长度}、{表达式:字符^长度}。
num = 23
str1 = f'py2202{num:0>5}'
print(str1) # 'py220200023'
str1 = f'py2202{num:0<5}'
print(str1) # 'py220223000'
str1 = f'py2202{num:x^5}'
print(str1) # 'py2202x23xx'
4. 作业
-
编写一个程序,交换指定字典的key和value。
例如:dict1={'a':1, 'b':2, 'c':3} --> dict1={1:'a', 2:'b', 3:'c'}dict1={'a':1, 'b':2, 'c':3} dict2={value:key for key,value in dict1.items()} print(dict2) -
编写一个程序,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
例如: 传入'12a&bc12d-+' --> 'abcd'
str1 = '12a&bc12d-+' result = (''.join(str(x) for x in str1 if 'a' <= x <= 'z' or 'A' <= x <= 'Z')) print(result) -
写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
例如: 'abc' -> 'Abc' '12asd' --> '12asd'
str1 = 'abc' x = str1[0] if x.islower(): str2 = str1.replace(x,chr(ord(x)-32),1) print(str2) -
写程序实现endswith的功能,判断一个字符串是否已指定的字符串结束
例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True 字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: Falsestr1 = 'abc231ab' str2 = 'ab1' print(str1[-len(str2):] == str2)
-
写程序实现isdigit的功能,判断一个字符串是否是纯数字字符串
例如: '1234921' 结果: True '23函数' 结果: False 'a2390' 结果: Falsestr1 = '1hh4654' for x in str1: if not ('0' <= x <= '9'): print('False') break else: print('True') -
写程序实现upper的功能,将一个字符串中所有的小写字母变成大写字母
例如: 'abH23好rp1' 结果: 'ABH23好RP1'
str1 = 'abH23好rp1' new_str = '' for x in str1: if 'a' <= x <= 'z': new_str += chr(ord(x)-32) else: new_str += x print(new_str) -
写程序获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
例如: 序列:[-7, -12, -1, -9] 结果: -1 序列:'abcdpzasdz' 结果: 'z' 序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98} 结果: 98
nums = 'abcdpzasdz'
if type(nums) == dict:
nums1 = {value: key for key,value in nums.items()}
max = list(nums1)[0]
for x in nums1:
if max < x:
max = x
else:
max = nums[0]
for x in nums:
if max < x:
max = x
print(max)
-
写程序实现replace函数的功能,将指定字符串中指定的旧字符串转换成指定的新字符串
例如: 原字符串: 'how are you? and you?' 旧字符串: 'you' 新字符串:'me' 结果: 'how are me? and me?'
str1='how are you? and you?' str2='you' str3='me' str0='' l=len(str2) l1=len(str1) index=0 while index
-
写程序实现split的功能,将字符串中指定子串作为切割点对字符串进行切割
例如:原字符串: 'how are you? and you?' 切割点: 'you' 结果: ['how are ', '? and ', '?']
str1 = 'how are you? and you?' str2 = 'you' list1 = [] str3 = '' len1 = len(str1) len2 = len(str2) x = 0 while x < len1: if str1[x:x+len2] == str2: list1.append(str3) str3 = '' x+= len2 else: str3 += str1[x] x+=1 list1.append(str3) print(list1) -
用思维导图总结四大容器:列表、字典、元组、集合
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2tot2NAY-1650638898775)(C:Users86134Pictures微信图片_20220422224657.jpg)]
能,将字符串中指定子串作为切割点对字符串进行切割
例如:原字符串: 'how are you? and you?' 切割点: 'you' 结果: ['how are ', '? and ', '?']
str1 = 'how are you? and you?'
str2 = 'you'
list1 = []
str3 = ''
len1 = len(str1)
len2 = len(str2)
x = 0
while x < len1:
if str1[x:x+len2] == str2:
list1.append(str3)
str3 = ''
x+= len2
else:
str3 += str1[x]
x+=1
list1.append(str3)
print(list1)
- 用思维导图总结四大容器:列表、字典、元组、集合
[外链图片转存中…(img-2tot2NAY-1650638898775)]



