字符間的相互轉化:
數字與字串之間的相互轉化
1、數字(整數與浮點數) --> 字串 :只需要在要轉化的數字前加str進行轉換就可以
num = 10.5
str_num = str(num)
print(str_num)
2、字串轉化為數字 --> 使用 int 或 float 方法進行轉化
1 整數字串轉化為數字 (當字串中只有數字是才可以進行轉換)
s = "10"
s_int = int(s)
print(s_int) # 10
s_float = float(s)
print(s_float) # 10.0
2 小數字串轉換為數字 ---> 小數的字串只能轉換為float型別
s = "10.5"
# s_int = int(s)
# print(s_int) # ValueError: invalid literal for int() with base 10: '10.5'
# python學習交流群:711312441
s_float = float(s)
print(s_float) # 10.5
3 將負數轉換為數字型別
s = "-.5"
print(float(s)) # -0.5
字串與串列之間的轉換 --> 字串與其他型別的轉換,需要字符首先轉換為串列,再進行其他型別的轉換
1、字串轉換為串列
1 每個字符轉換為一個串列的值
s = "i am a boy"
ls = list(s)
print(ls)
2 字串以指定字符進行切割
s = "i am a boy"
new_str = s.split() # ----> 以空格作為默認切割字符
print(new_str) # ['i', 'am', 'a', 'boy']
2、串列轉換位字串
s1 = "".join(new_str)
print(s1) # iamaboy
s2 = " ".join(new_str)
print(s2) # i am a boy
串列轉換為元組及集合
字符轉換為其他型別只需要使用相應的方法就可以
new_list = ['i', 'am', 'a', 'boy']
print(tuple(new_list))
print(set(new_list))
字串轉換為其他型別的字串
1、字串轉換為元組型別
ls = []
source = "id=76&video_uri=person_card"
for i in source.split("&"):
(k,y) = i.split("=")
ls.append((k,y))
print(ls)
2、字串轉換為字典
dic = {}
for i in source.split("&"):
k,v = i.split("=")
dic[k] = v
print(dic)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/538144.html
標籤:其他
下一篇:十六進制數轉換為八進制數
