Python — 2.基本数据类型

Python — 2.基本数据类型

# 1、数字类型
# (1)测试类型函数:type()
# (2)十进制转换为二进制数:bin()
bin(4)
'0b100'
# (3)十进制转换为八进制数:oct()
oct(45)
'0o55'
# (4)十进制转换为十六进制:数hex()
hex(45)
'0x2d'

 

2、format()

# (1)"{}".format()
print("{}曰:学而时习之,不亦说乎。".format("孔子"))
print("{}曰:学而时习之,不亦{}。".format("孔子","说乎"))
print("{1}曰:学而时习之,不亦{0}。".format("说乎","孔子"))

 (2)组合使用

 

 

 

# (2)": <填充的单个字符> <对齐> <宽度> , <.精度> <类型>"
s = "等级考试"
"{:25}".format(s) #左对齐,默认
'等级考试 '
"{:^25}".format(s) #居中对齐^
' 等级考试 '
"{:>25}".format(s) #右对齐>
' 等级考试'
"{:*^25}".format(s) #居中对齐且填充*号
'**********等级考试***********'
"{:十^25}".format(s) #居中对齐且填充汉字“十”
'十十十十十十十十十十等级考试十十十十十十十十十十十'
"{:^1}".format(s) #z指定宽度为1,不足变量s的宽度
'等级考试'
"{:.3}".format(123.456)
'1.23e+02'
"{:.2}".format(123.456)
'1.2e+02'
"{:.2f}".format(12345.67890)
'12345.68'
"{:>25.3f}".format(12345.67890)
' 12345.679'
"{:.5}".format("全国计算机等级考试")
'全国计算机'

# <类型>:输出整数和浮点数类型
# b:输出整数的二进制方式
# c:输出整数对应的Unicode字符
# d:输出整数的十进制方式
# o:输出整数的八进制方式
# x:输出整数的小写十六进制方式
# X:输出整数的大写十六进制方式
"{0:b},{0:c},{0:d},{0:o},{0:x},{0:X}".format(425)
'110101001,Ʃ,425,651,1a9,1A9'


# 3、操作符
# (1)连接两个字符串x与y:x+y
# (2)复制n次字符串x:x*n
# (3)如果x是s的子串,返回True,否则返回False:x in s


# 4、字符串处理函数
# (1)全部字符小写
str.lower()
# (2)全部字符大写
str.upper()

# (3)返回一个列表,由str根据sep被分割的部分构成
str.split(sep=None)
# 例:
a = "ab ced kll"
a.split()
['ab', 'ced', 'kll']
a.split("e")
['ab c', 'd kll']

# (4)sub子串出现的次数
str.count(sub)
# 例:
a = "adfdsfdddfisdhfidff545545"
a.count('d')

# (5)返回字符串str的副本,所有old子串被替换为new
str.replace(old,new)
# 例:
"abcdbdddfef".replace("cd","**")
'ab**bdddfef'

# (6)字符串居中函数,fillchar参数可选
str.center(width,fillchar)
# 例:
"ab".center(10)
'    ab    '
"ab".center(10,"*")
'****ab****'

# (7)从字符串str中去掉在其左侧和右侧chars中列出的字符
str.strip(chars)
# 例:
"abcdab".strip("ab")
'cd'
"abcabdab".strip("ab")
'cabd'

# (8)将iter变量的每一个元素后增加一个str字符串
str.join(iter)
# 例:
# 链接
"*".join("abcd")
'a*b*c*d'

# (9)查找
# 这是查找它的位置,这30是从30这开始查找,如果没有这30就是从开始开始查找。
s = "The python language is a cross platfoorm language."
print(s.find('language',30))
41
print(s.find('language'))
11

 

posted @ 2020-11-03 11:41  淇凌  阅读(67)  评论(0编辑  收藏  举报