整形与字符串的魔法
- int
将字符串转换为数字
a = 123
print(type(a),a)
a = "123"
print(type(a),a)
b = int(a)
print(type(b),b)
num = "0011"
v = int(num,base=16) base的意思是将(通常是一个字符串)按照base进制转换成整数。
print(v)
- bit length
age = 3
1 = 1
2 = 10
3 = 11
4 = 100
5 = 101
当前数字的二进制,至少用n位表示
r = age.bit_length
字符的"魔法"
test ="sunpengfei"
# 首字母变成大写:
# v = test.capitalize()
# print(v)
#所有字母变小写,casefold 更牛逼一点,很多未知的相应变成小写
# v1 = test.lower()
# print(v1)
# v2 = test.casefold()
# print(v2)
# 设置宽度,并将内容居中
# 20代指宽度
# * 空白内容填充,一个字符,可有可无
# v = test.center(20,"*")
# print(v)
count的意思是去字符串中寻找,下面的例子是先找'p',最后输出是多少个p的次数
# test = "penphypenphy"
# v = test.count('p')
# print(v)
下面的例子是先找'p',然后输出在2-5个字符之间有多少个p的次数
# test = "penphypenphy"
# v = test.count('p',2,5)
# print(v)
# test = "penphypenphy"
# v = test.endswith('hy') 以什么什么为结尾
# v = test.startswith('pen') 以什么什么为开头
# print(v)
坎坷困难会让你不断的强大起来 -- 前提是你别怂