内置函数(一)

mac2022-06-30  93

数字类型

定义方法

int(x, base=10)

x:可以是数字字符串也可以是数值

base:将几进制转换为十进制

a = int('1234') # 将字符串的‘1234’转为整型的1234 print(type(a)) # <class 'int'> #但是如果是带有小数的字符串便会报错 b = int('1.0') #ValueError: invalid literal for int() with base 10: '1.0' c = int('1101',2) # 将字符串的二进制数转为整型十进制数。 print(b) # 13 d = int('1101',8) # 将字符串的八进制数转为整型十进制数。 print(c) # 577 e = int('1101',16) # 将字符串的16进制数转为整型十进制数。 print(d) # 4353

float()

虽然带有小数的字符串无法转为整型,但是可以转为浮点型:

a = float('1.0') print(a) # 1.0 b = float('-12345') print(b) # -12345.0

字符串类型

定义方法

s1 = 'Gredae' s2 = "Gredae" s3 = '''Hello ##可以跨行 Gredae''' s4 = """Hello ##可以跨行 Gredae""" print(s1) # Gredae print(s2) # Gredae print(s3) # Hello Gredae print(s4) # Hello Gredae

内置方法(常用)

取值(str[])

s = 'Hello World!' print(s[4]) # o

切片(str[::])

s = 'Hello World!' print(s[:]) # Hello World! ##从头到尾输出 print(s[2:]) # llo World! ##从索引为2开始到尾输出 print(s[:7]) # Hello W ##从字符串头到索引为7(取不到索引为7的字符)的字符输出 print(s[::2]) # HloWrd ##从字符串头到尾,步长为2输出 print(s[::-1]) # !dlroW olleH ##字符串从头到尾逆序输出

长度(len(str))

s = 'Hello' s1 = 'Hello World!' print(len(s)) # 5 print(len(s1)) # 12

成员运算(in 和 not in)

s = 'Hello World!' print('a' in s) # False ##字符'a'在字符串s中 print('a' not in s) # True ##字符'a'不在字符串s中

移除两端字符(strip)

s = ' Hello World ' print(s.strip()) # Hello World ##默认移除两端空格字符串 s1 = '*****Hello World*****' print(s.strip('*')) # Hello World ##移除指定字符串

将字符串进行切割(split)

s = 'my name is Gredae' print(s.split()) # ['my', 'name', 'is', 'Gredae'] ##默认以空格字符切割并返回字符串列表 s1 = '192.168.1.1' print(s1.split('.')) # ['192', '168', '1', '1'] ##以指定字符串切割并返回字符串列表

进行字符串循环

s = 'my name is Gredae' for i in s: print(i,end=' ') #m y n a m e i s G r e d a e ##end(以什么结尾,默认是换行)

字符串进行替换(replace)

s = '192.168.1.1' print(s.replace('.',',')) # 192,168,1,1 ##将字符串'.'替换成字符串','

将字符串列表转为字符串(str.join)

s = ['192', '168', '1', '1'] print('[.]'.join(s)) # 192[.]168[.]1[.]1 #以指定字符串为间隔拼接字符串列表

判断字符串是否都为数字(isdigit)

s = '123456' print(s.isdigti()) # True s1 = 'abc123' print(s1.isdigit()) # False

将字符从小写转成大写(upper)和从大写转成小写(lower)

s = 'aBcDe' print(s.lower()) # abcde print(s.upper()) # ABCDE

查找第一个出现指定字符串的起始索引(find)

s = 'my name is Gredae' print(s.find('is')) # 8 print(s.find(' G')) # 10 print(s.find('*')) # -1 ##若找不到指定的字符便返回-1

统计指定字符串出现的次数(count)

s = 'abcdecdhi' print(s.count('ab')) # 1 print(s.count('d')) # 2

转载于:https://www.cnblogs.com/Gredae/p/11294810.html

最新回复(0)