如有错误,敬请斧正。
int
int() 函数用于将一个字符串或数字转换为整型。
x
– 字符串或数字。base
– 进制数,默认十进制。>>> int(1.0)
1
>>> int('1.1')
Traceback (most recent call last):
File "" , line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.1'
>>> int(123)
123
>>> int('123')
123
>>> int('123.1')
Traceback (most recent call last):
File "" , line 1, in <module>
ValueError: invalid literal for int() with base 10: '123.1'
>>> int('a')
Traceback (most recent call last):
File "" , line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
>>> int('1222ddd')
Traceback (most recent call last):
File "" , line 1, in <module>
ValueError: invalid literal for int() with base 10: '1222ddd'
>>>
float
float() 函数用于将整数和字符串转换成浮点数。
>>> float(10)
10.0
>>> float(10.00)
10.0
>>> float('10.1')
10.1
>>> float('10')
10.0
>>> float('10aaa')
Traceback (most recent call last):
File "" , line 1, in <module>
ValueError: could not convert string to float: '10aaa'
>>>
# isdigit() 方法检测字符串是否只由数字组成。
str1 = '123'
str2 = '123a'
if str1.isdigit():
int(str1)
if str2.isdigit():
int(str2)
str
函数将对象转化为字符串。
class str(object='')
object – 对象。
>>> str(123)
'123'
>>> str({
"key": 123, "str": "abc" })
"{'key': 123, 'str': 'abc'}"
>>> str([ 1, 2, 3 ])
'[1, 2, 3]'
>>> str(('a', 'b', 'c'))
"('a', 'b', 'c')"
>>> str({
'a', 'b', 'c' })
"{'a', 'c', 'b'}"
>>>
tuple
tuple 函数将可迭代系列(如列表)转换为元组。
tuple( iterable )
iterable
– 要转换为元组的可迭代序列。>>> tuple(['a', 'b', 'c'])
('a', 'b', 'c')
>>> tuple('abc')
('a', 'b', 'c')
>>>
list
list() 方法用于将元组或字符串转换为列表。
list( seq )
seq
– 要转换为列表的元组或字符串。>>> list('abc')
['a', 'b', 'c']
>>> list('123')
['1', '2', '3']
>>> list((1, 2, 3))
[1, 2, 3]
>>> list(('a'))
['a']
>>>
dict
dict() 函数用于创建一个字典。
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
>>>dict() # 创建空字典
{
}
>>> dict(a='a', b='b', t='t') # 传入关键字
{
'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典
{
'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代对象方式来构造字典
{
'three': 3, 'two': 2, 'one': 1}
>>>
set()
set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
class set([iterable])
>>> set('abc')
{
'b', 'a', 'c'}
>>> set(('a', 'b'))
{
'b', 'a'}
>>> set(['a', 'b', 'c'])
{
'b', 'a', 'c'}
>>> x = set('runoob')
>>> y = set('google')
>>> x | y
{
'e', 'b', 'n', 'g', 'r', 'o', 'l', 'u'}
>>> x & y
{
'o'}
>>> x - y
{
'b', 'n', 'r', 'u'}
>>>