内置对象相关方法(一)
1 python中内置对象常用的方法主要有:
1. 整数/浮点数
2. 字符/字符串
3. 列表/元组
4. 字典
5. 集合
字符串String
- 定义: 一串字符! 用 ""或'' 引起来! 字符串是字符串列表,索引从0开始!
- 字符串是字符串的列表! 可以通过索引访问,索引从0开始,-1表示最后一个
- 索引不能操作范围!
- 字符串不可变!
- 编列
-
- 表示连接: 控制台 input() 方法输入的内容都是字符串!
- 切片 [开始:结束:步长] [::-1]倒序
- 格式化字符串
name = tom
age = 20 # 方法1.使用占位符格式化
print("名字:%s,年龄:%d"%(name,age))
# 方法2:格式化
print(f"名字:{name},年龄:{age}")
# 方法3:格式化 pri
nt("名字:{0}年龄{1}".format(name,age))
- 转义
···
\' 转义
\t 制表符等于4个空格(Tab)
\n 换行 \r\n linux换行
\ 续行(该行还未结束,下一样继续)
···
内置方法
1. len(字符串) # 长度
2. chr() 转化为字符 chr(97)--a chr(65)--A
3. ord(字符)转化为对应ASCII编码 ord('A')-->65
4. find(字符) 找不到返回-1
5. index(字符)找不到报错
6. replace('老字符串','新字符串') 替换
7. splite('字符') 拆分 返回列表!
8. lower(字符串) 转为小写
9. upper(字符) 转为大写
10. strip(字符串) 去掉两遍空格 rstrip(字符串) 去掉右边空格 lstrip(字符串)去左边
11. not in 'hello' 判断是否存在!
# 赋值
s = 'hello'
s[0] --->第一个
s[-1] --->最后一个
# 字符串不可变
s = 'helloWorld'
s[5] ='w' #报错 str not support item assignment
# 遍历
str01='hello'
for i in hello:
print(i)
# 编列索引和值
for i,v in enumerate(str01):
print(f'第{i},个值:{v}')
# 生成
a-z print(chr(random.choice(range(97,123))))
# A-Z
print(chr(random.choice(range(65,91))))