數據類型轉換:將自身數據類型轉化成新的數據類型,並擁有新數據類型相關操作的過程; 為方便更好的幫助處理業務,將數據變更為更適合業務場景的類型; a = '1', 此時想使用數字的數學操作,就需要先將字元串轉化為數字類型; 1.數字與字元串間的轉換 # 字元串轉換成整數 a = '34' b = in ...
數據類型轉換:將自身數據類型轉化成新的數據類型,並擁有新數據類型相關操作的過程;
為方便更好的幫助處理業務,將數據變更為更適合業務場景的類型;
a = '1', 此時想使用數字的數學操作,就需要先將字元串轉化為數字類型;
1.數字與字元串間的轉換
# 字元串轉換成整數
a = '34'
b = int(a)
print(b) # 34
# 此時字元串內必須是整數,否則會報錯
# print(int('45.6')) # ValueError: invalid literal for int() with base 10: '45.6'
# 字元串轉換成浮點數
print(float('45.6')) # 45.6
print(type(float('45.6'))) # <class 'float'>
print(float('45')) # 45.0
# 數字轉換成字元串
c = 34
print(str(c)) # 34
print(type(str(c))) # <class 'str'>
print(str(45.6)) # 45.6
2.字元串與列表之間的轉換
字元串轉換成列表:spring.split(sep=分割符, maxsplit=最大分割次數);
列表轉換成字元串:'分割符號'.join(可迭代對象);可迭代對象存儲的數據不能是數字類型;
str_test = 'i am a teacher'
print(str_test.split()) # ['i', 'am', 'a', 'teacher'] (預設分割符是空格、預設分割次數為全部)
print(str_test.split(maxsplit=2)) # ['i', 'am', 'a teacher']
print('wer#ty#67'.split('#', 1)) # ['wer', 'ty#67']
# 若指定的分割符不存在,則完整字元串作為一個元素存入列表
print('i love you'.split('!')) # ['i love you']
# 分割符不能是空字元串,會報錯
# print(a.split('')) # ValueError: empty separator
text = "23,王偉,2-1"
print(text.split(',')) # ['23', '王偉', '2-1'] (此時2-1屬於字元串)
# print(' '.join(['python', 56])) # TypeError: sequence item 1: expected str instance, int found
print(' '.join(['python', 'go'])) # python go
print('!!!'.join(('python', 'go'))) # python!!!go
print(' '.join({'python', 'go'})) # go python
print(' '.join({'name': 'll', 'height': 178})) # name height (字典拼接的是key)
3.字元串類型與比特類型的轉換
比特類型是一種特殊的二進位的數據流, bytes;
可以看做是一種特殊的字元串,寫法是字元串前加b;
字元串轉換bytes, string.encode(encoding=編碼格式, errors='strict')
encoding是編碼格式、預設是utf-8, 還可以是ascii或gbk等,errors是遇到錯誤時的操作,預設是strict直接拋異常、也可以指定為ignore, 忽略錯誤;
bytes轉換成字元串,bytes.decode(encoding=編碼格式,errors='strict')
a = b'hello world'
print(a) # b'hello world'
print(type(a)) # <class 'bytes'>
# bytes類型也可以使用一些字元串的方法, 可以利用dir()函數查看所用相關方法
print(dir(bytes))
'''
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'fromhex', 'hex', 'index', 'isalnum',
'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
'''
# replace()
new_a = a.replace(b'h', b'aaa') # 註意傳的參數也要是比特類型
print(new_a) # b'aaaello world'
# 比特數據中不能帶中文,可以先將字元串轉換下
# b = b'你好 world' # SyntaxError: bytes can only contain ASCII literal characters.
# print(b)
b = '你好 world'
new_b = b.encode('utf-8')
print(new_b) # b'\xe4\xbd\xa0\xe5\xa5\xbd world'
reduction_b = new_b.decode('utf-8')
print(reduction_b) # 你好 world
4.列表、元組、集合間的轉換
直接調用相關內置函數即可;
list()、tuple()、set()
test_list = [34, 56]
tuple_test = tuple(test_list)
print(tuple_test) # (34, 56)
print(type(tuple_test)) # <class 'tuple'>
new_tuple = (45,)
set_test = set(new_tuple)
print(set_test) # {45}
print(type(set_test)) # <class 'set'>
print(list(set_test)) # [45]
print(type(list(set_test))) # <class 'list'>