各个数据类型的内置方法
整形和浮点型的内置方法
# 1、定义:
# 1.1 整型int的定义
age=10 # 本质age = int(10)
# 1.2 浮点型float的定义
salary=3000.3 # 本质salary=float(3000.3)
# 注意:名字+括号的意思就是调用某个功能,比如
# print(...)调用打印功能
# int(...)调用创建整型数据的功能
# float(...)调用创建浮点型数据的功能
# 1、数据类型转换
# 1.1 int可以将由纯整数构成的字符串直接转换成整型,若包含其他任意非整数符号,则会报错
>>> s = '123'
>>> res = int(s)
>>> res,type(res)
(123, <class 'int'>)
>>> int('12.3') # 错误演示:字符串内包含了非整数符号.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.3'
# 1.2 进制转换
# 十进制转其他进制
>>> bin(3)
'0b11'
>>> oct(9)
'0o11'
>>> hex(17)
'0x11'
# 其他进制转十进制
>>> int('0b11',2)
3
>>> int('0o11',8)
9
>>> int('0x11',16)
17
# 1.3 float同样可以用来做数据类型的转换
>>> s = '12.3'
>>> res=float(s)
>>> res,type(res)
(12.3, <class 'float'>)
数字类型主要就是用来做数学运算与比较运算,因此数字类型除了与运算符结合使用之外,并无需要掌握的内置方法
字符串
# 定义:在单引号\双引号\三引号内包含一串字符
name1 = 'jason' # 本质:name = str('任意形式内容')
name2 = "lili" # 本质:name = str("任意形式内容")
name3 = """ricky""" # 本质:name = str("""任意形式内容""")
数据类型转换:str()可以将任何数据类型转换为字符串类型,例如:
python(str([1,2,3]))#list->str
<<class 'str'>>
python(type(str({'name':'jaswe','age':18})))
<class 'str'># dict->str
print(type(str({1,2,3,4})))
print(type(str((1,2,3))))
<class 'str'>
<class 'str'>
基础
>>> str1 = 'hello python!'
# 1.按索引取值(正向取,反向取):
# 1.1 正向取(从左往右)
>>> str1[6]
p
# 1.2 反向取(负号表示从右往左)
>>> str1[-4]
h
# 1.3 对于str来说,只能按照索引取值,不能改
>>> str1[0]='H' # 报错TypeError
# 2.切片(顾头不顾尾,步长)
# 2.1 顾头不顾尾:取出索引为0到8的所有字符
>>> str1[0:9]
hello pyt
# 2.2 步长:0:9:2,第三个参数2代表步长,会从0开始,每次累加一个2即可,所以会取出索引0、2、4、6、8的字符
>>> str1[0:9:2]
hlopt
# 2.3 反向切片
>>> str1[::-1] # -1表示从右往左依次取值
!nohtyp olleh
# 3.长度len
# 3.1 获取字符串的长度,即字符的个数,但凡存在于引号内的都算作字符)
>>> len(str1) # 空格也算字符
13
# 4.成员运算 in 和 not in
# 4.1 int:判断hello 是否在 str1里面
>>> 'hello' in str1
True
# 4.2 not in:判断tony 是否不在 str1里面
>>> 'tony' not in str1
True
# 5.strip移除字符串首尾指定的字符(默认移除空格)
# 5.1 括号内不指定字符,默认移除首尾空白字符(空格、\n、\t)
>>> str1 = ' life is short! '
>>> str1.strip()
life is short!
# 5.2 括号内指定字符,移除首尾指定的字符
>>> str2 = '**tony**'
>>> str2.strip('*')
tony
# 6.切分split
# 6.1 括号内不指定字符,默认以空格作为切分符号
>>> str3='hello world'
>>> str3.split()
['hello', 'world']
# 6.2 括号内指定分隔字符,则按照括号内指定的字符切割字符串
>>> str4 = '127.0.0.1'
>>> str4.split('.')
['127', '0', '0', '1'] # 注意:split切割得到的结果是列表数据类型
# 7.循环
>>> str5 = '今天你好吗?'
>>> for line in str5: # 依次取出字符串中每一个字符
... print(line)
...
今
天
你
好
吗
?
重点掌握
- strip, lstrip, rstrip
- lower(), upper()
- startswith, endswith
- 格式化输出之format
- format的其他使用方式
- split,rsplit
- join
- replace
- isdigit
1.strip,lstrip,rstrip
str1='###Erfd###'
print(str1.strip('#'))左右两边
print(str1.lstrip('#'))左边
print(str1.rstrip('#'))右边
Erfd
Erfd###
###Erfd
2.lower(),upper()
str2='saEFDfef'
print(str2.lower())#小写
print(str2.upper())#大写
saefdfef
SAEFDFEF
3.startswith,endswith
# startswith()判