1.格式字符串:在字符串中通过格式占位符来表示字符串中变化的部分
语法:包含格式占位符的字符 % (给格式占位赋值的数据列表)
说明:格式占位符:
%s - 字符串
%d - 整数
%.Nf - 小数,N可以约束小数点后面的小数位数
%c - 字符,可以将整数转换为字符
name = input('姓名:')
age = int(input('年龄: '))
money = float(input('月薪:'))
message = '%s今年%d岁,月薪:%.2f' % (name,age,money)
# message = name + '今年' + age + '岁'
print(message)
练习:输入学生姓名,年龄,性别,以“xx今年XX岁,性别:X”
name = input('姓名')
age = int(input('年龄'))
sex = input('性别')
message1 = '%s今年%d岁,性别:%s' % (name,age,sex)
print(message1)
2.常用对象方法
字符串1.count(字符串2) - 统计字符串2在字符串1中出现的次数
str1 = 'ashdjadadskjsasd'
print(str1.count("a"))
字符串1.find(字符串2) - 在字符串1中查找字符串2第一次出现的位置,如果找不到返回-1,找到了返回第一个字符的下标
字符串2.find(字符串2,开始下标,结束下标) - 在字符串1中开始下标到结束下标中查找字符串2第一次出现的位置(不包含结束下标)
index的功能和find一样,只是如果字符串2不存在的时候会报错
字符串1.isdigit() - 判断字符串1中是否只有数字字符
字符串1.isnumeric() - 判断字符串1是否是数字字符串(可以检查中文数字)
字符串1.join(序列) - 将序列中的元素用字符串1连接在一起产生一个新的字符串
max(序列),min(序列) - 求序列中元素的最大值和最小值
练习:打印字符串中每个字符出现的次数
打印字符串中出现次数最多字符和对应的次数
'how are you?oh-' 打印:o 3次
string = 'how are you?oh-'
num1 = 0
str3 = ''
for x in string:
num = string.count(x)
if num > num1:
num1 = num
str3 = x
print(str3,num1)
练习:在字符串中'and you? how are you? you! '找出you的下标
string3 = 'and you? how are you? you!'
string4 = 'you'
s = len(string3)
c = 0
while True:
x = string3.find(string4,c,s)
c = x + 1
if x == -1:
break
else:
print(x)
练习:自己实现join的功能,给字符串1,和字符串2,用字符串1将字符串2中所有的字符串连接起来
str2 = 'ag23dfsfs345d',stri = '+', 数字相加
str2 = 'ag23dfsfs345d'
str1 = '+'
new_str4 = ''
s = ''
for x in str2:
if '0' <= x <= '9':
new_str4 += x
s = str1.join(new_str4)
print(s)
numbers_1 = [1,20,100,'qww',200,2333,'qww']
del numbers_1[2]
print(numbers_1)
- 列表.remove(元素) - 将指定列表中第一个指定元素删除
注意:如果元素不存在,会报错
numbers_1.remove('qww')
print(numbers_1)
3)列表.pop() - 移除列表中最后一个元素,返回被移除的元素
列表.pop(下标) - 移除列表中指定下标对应的元素
把一个元素从列表中取出或销毁 del/pop
4)清空:列表.clear() - 删除列表中所有的元素
7.改 - 修改列表元素
列表[下标] = 新值 - 将列表中指定下标对应的元素改成新值
nums = [1,2,3]
nums[0] = 100
print(nums)
8.in/not in
元素 in 列表 --- 判断列表中是否包含指定的元素