基本資料型別及常用魔法
阿新 • • 發佈:2018-12-26
一. 數字 int
1. int 將字串轉換成數字
a="123" print(type(a),a) a=int(a) print(type(a),a)
#指定字串進位制 a="0011" a=int(a,base=16) print(a)
2. bit_length 當前數字轉換為二進位制數至少需要幾位數
a=11 b = a.bit_length() print(b)
二. 字串str
1. capitalize 首字母大寫
str='hello' v=str.capitalize() print(v)
執行結果:
Hello
2. casefold 轉換為小寫,與lower功能相同,但比lower功能強大
str='HeLLo' v=str.casefold() print(v)
執行結果:
hello
3. center 將字串放在中間,並用指定字元(0或1個,不指定預設空格)填充兩邊,使達到指定長度
str='hello' v=str.center(20,"#") print(v)
執行結果:
#######hello########
4. count 計算字串中指定子字串的個數,可指定其實結束位置,左閉右開
str="buhuanfhgujk" v1=str.count('u') v2=str.count('u',0,10) v3=str.count('u',0,9) print(v1,v2,v3)
執行結果:
3 3 2
5. endswith 判斷是否以指定字串結尾,可指定判定區間,左閉右開,startswith同
str="shueign" v=str.endswith('gn') v1=str.endswith('h',0,1) v2=str.endswith('h',0,2) print(v,v1,v2)
執行結果:
True False True
6. find 找到指定字串的位置,未找到返回-1,左閉右開
str="husjgjabugblangu" v=str.find('gj') v1=str.find('g',5,9) v2=str.find('g',5,10) print(v,v1,v2)
執行結果:
4 -1 9
7. format 將一個字串中的佔位符替換為指定的值
str='I am {name}.I am {year}' v=str.format(name="hao",year="20") print(v) str1='I am {0}.I am {1}' v1=str1.format("hao","20") print(v1)
# 格式化,傳入的值必須是 {"name": 'alex', "a": 19} test = 'i am {name}, age {a}' v1 = test.format(name='df',a=10) v2 = test.format_map({"name": 'alex', "a": 19})
8. isalnum 字串中是否只包含 字母和數字
str="[email protected]" v1=str.isalnum() print(v1)