1.整数和数字组成的字符串之间的转换:
>>> int("123")
123
>>> str(123)
'123'
>>> int("1.23") #浮点数字符串和整型不能互转,需要借助中间类型(float)
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: '1.23'
2.浮点数和浮点数构成字符串之间的转换:
>>> int(1.23)
1
>>> float("1.23")
1.23
>>> str(1.23)
'1.23'
3.字母和数字之间的转换:
>>> ord("a")
97
>>> chr(65)
'A'
>>>
4.字符串可以直接转成列表(元素类型为str)、元组(字符类型的元素)、字典(key类型为str)
>>> a="abcd123"
>>> list(a)
['a', 'b', 'c', 'd', '1', '2', '3']
>>> tuple(a)
('a', 'b', 'c', 'd', '1', '2', '3')
>>> a="abc"
>>> {}.fromkeys(a)
{'a': None, 'c': None, 'b': None}
>>>
5. 列表(所有元素类型为str)或元组(所有元素类型为str)、字典(所有key为str型)转换成字符串:
>>> a=["a","b","c","1","2","3"]
>>> "".join(a) #参数seq元素必须为字符串类型
'abc123'
>>> a=("a","b","c","1","2","3")
>>> "".join(a)
'abc123'
>>>>>> a={"a":1,"b":2,"c":3,"1":4,"2":5,"3":6}
>>> "".join(a)
'acb132'