內建函式(一)

2022-08-23 00:42:08 字數 3240 閱讀 7712

x:可以是數字字串也可以是數值

base:將幾進製轉換為十進位制

a = int('1234')  # 將字串的『1234』轉為整型的1234

print(type(a)) # #但是如果是帶有小數的字串便會報錯

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

雖然帶有小數的字串無法轉為整型,但是可以轉為浮點型:

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

內建函式一

s for i in range 10 print i s1 def func print 123 func print eval s print exec s1 牛逼 不能用print hash yulin print help list help dict def func pass print...

Python內建函式 一

abs 是乙個取絕對值的函式,使用起來相對比較簡單。print abs 1 結果1 finished in 0.1s 原始碼中對它的描述比較簡單是這麼介紹的 abs number number return the absolute value of the argument.在入參中增加了型別的檢...

python內建函式一

內建函式 1.abs number 用法 返回數字的絕對值 2.all iterable 用法 如果iterable的所有元素都是真值,就返回true,否則返回false 3.any iterable 用法 如果iterable的所有元素都是假值,就返回false,否則返回true 4.ascii ...