数字与字符串的魔法方法

一、数字(int)

  • int()

将字符串转换为数字

1 a = "123"
2 print(type(a),a)
3 #结果:<class 'str'> 123
4 b = int(a)
5 print(type(b),b)
6 #结果为:<class 'int'> 123

将16进制以10进制转换并输出

1 num = '0011'
2 v = int(num,base=16)
3 print(v)
4 #结果为:17
  • bit_lenght()
 1 # 当前数字的二进制,至少用n位表示
 2 age = 3
 3 #3==》11
 4 r = age.bit_length()
 5 print(r)
 6 #结果:2
 7 new_age = 4
 8 #4==》100
 9 new_r = new_age.bit_length()
10 print(new_r)
11 #结果:3

二、字符串(str)

  • capitalize()
1 #首字母大写
2 test = 'soLitary'
3 v = test.capitalize()
4 print(v)
5 #结果:Solitary
  • casefold()     /          lower()
1 #所有变小写,casefold更牛逼,很多未知的对相应变小写
2 test = 'soLitary'
3 v1 = test.casefold()
4 #结果:solitary
5 print(v1)
6 v2 = test.lower()
7 print(v2)
8 #结果:solitary
  • center()   /    ljust()    /      rjust()     /      zfill()
 1 '''设置宽度,并将内容居中;20 代指总长度;*  空白未知填充,一个字符,可有可无'''
 2 test = 'soLitary'
 3 v1 = test.center(20,'')
 4 print(v1)
 5 #结果:爱爱爱爱爱爱soLitary爱爱爱爱爱爱
 6 v2 = test.ljust(20,'*')
 7 print(v2)
 8 #结果:soLitary************
 9 v3 = test.rjust(20,'*')
10 print(v3)
11 #结果:************soLitary
12 v4 = test.zfill(20)
13 print(v4)
14 #结果:000000000000soLitary
  • count()

     

1 #去字符串中寻找,寻找子序列的出现次数
2 test = 'soLitary'
3 v1 = test.count('it')
4 print(v1)
5 #结果:1
6 v2 = test.count('it',5,6)
7 #在索引值为5,6里面去找
8 print(v2)
9 #结果:0

    

猜你喜欢

转载自www.cnblogs.com/dsynb/p/9059611.html
今日推荐