常用数据类型及其方法

今日总结

常用的数据类型及其方法。

主要内容:

1. int

int(x, base=10)

int返回一个使用数字或是字符串x生成的整数对象,或者没有实参时返回0.

int内置方法第二个参数base指定进制时,第一个参数是必须是字符串、bytes类型或是表示进制为base的bytearray实例对象。

具体使用方法如下:

>>> a = 3
>>> a
3
>>> a = int(4)  # 常用定义整数方式
>>> a
4
>>> a = int()   # 不带参数时默认为0
>>> a
0
>>> a = int('1111', 2)
>>> a
15
>>> a = int('0xff', 16) # 16进制转换为10进制
>>> a
255

 与进制相关的内置函数还有oct(),hex(), bin() 3个内置函数,使用方法与int类似。

oct(x)

将一个整数转换为前缀为‘0o’的八进制字符串

>>> oct(18)
'0o22'
>>> oct(-12)
'-0o14'

bin(x)

将一个整数转换为前缀为‘0b’的二进制字符串

>>> bin(100)
'0b1100100'
>>> bin(-100)
'-0b1100100'

hex(x)

 将一个整数转换为前缀为‘0x’的十六进制字符串

>>> hex(32)
'0x20'
>>> hex(-1)
'-0x1'

此处补充一点,当想要把整数转换成不带前缀的字符串的时候,可以使用%或者format方法格式化。

>>> '%#o %o' % (12, 12)
'0o14 14'
>>> '%#x %x' % (12, 12)
'0xc c'
>>> format(12, '#b'), format(12, 'b')    # 二进制只能使用format函数格式化不带前缀的字符串
('0b1100', '1100')

2. float

 float([x])

返回从数字x或字符串x生成的浮点数。

float方法可以接受几种特殊的字符串,如‘NAN’ 非数字,‘INF’无穷大,还有科学计数法的字符串。

 

>>> float(1.2)
1.2
>>> float('1.2333')
1.2333
>>> float('1e-3')
0.001
>>> float('2e3')
2000.0
>>> float('inf')
inf

3. str

3.1  定义 

str(object='')

返回object的字符串形式,没有参数时返回空字符串。

>>> str('123')
'123'
>>> str(dict(name='xiaowang', age=18))
"{'name': 'xiaowang', 'age': 18}"
>>> str()
''

3.2  字符串的方法

先声明,字符串是不可变类型,返回的都是原字符串的副本,方法中对字符串的操作并不会改变原有字符串。

重点掌握的几个方法

1、strip, lstrip, rstrip

移除字符串中前后的指定字符,默认为移除前后的空格。

>>> ' hello, world  '.strip()
'hello, world'
>>> ' hello, world  '.lstrip()         # 移除左边的空格
'hello, world  '
>>> ' hello, world  '.rstrip()      # 移除右边的空格
' hello, world'
>>> '!$$hello, world$$'.strip('!$')    # 可以指定多个字符,并移除这些字符
'hello, world'

2、 lower,upper

将字符串转换为全小写和全大写

>>> s = 'HeLLo, WorLd'
>>> s.lower()
'hello, world'
>>> s.upper()
'HELLO, WORLD'

3、 startswith, endswith

endswith(suffix[, start[, end]])
startswith(prefix[, start[, end]])

检查字符串是否是以指定的字符串的开始或结束的,这个方法还有两个参数,可以从指定的位置开始和指定的位置结束检查字符串。

>>> s = 'hello, world'
>>> s.startswith('he')
True
>>> s.endswith('ld')
True
>>> s.endswith('ld', 3, -2)
False

4、 format

format方法有3种占位格式化字符串的方式。分别是默认的顺序占位,或是按参数索引占位,或是关键字参数占位。

>>> 'name: {}, age: {}'.format('laowang', 18)
'name: laowang, age: 18'
>>> 'name: {0}, age: {1}, name2: {0}'.format('laowang', 18)
'name: laowang, age: 18, name2: laowang'
>>> 'name: {name}, age: {age}'.format(name='laowang', age=18)
'name: laowang, age: 18'  

此外format的具体参数格式十分多,可以参阅官方文档

>>> '{:^10}'.format('*')
'    *     '

5、 split, rsplit

split(sep=None, maxsplit=-1)

返回一个由指定字符串分割原字符串的列表。maxsplit参数最大分割次数,默认全部分割。rsplit是从右侧开始分割,基本与split一样。

>>> 'a b c d e e'.split()
['a', 'b', 'c', 'd', 'e', 'e']
>>> 'a b c d e e'.split(' ', 3)
['a', 'b', 'c', 'd e e']
>>> 'a b c d e e'.rsplit()
['a', 'b', 'c', 'd', 'e', 'e']
>>> 'a b c d e e'.rsplit(' ', 3)
['a b c', 'd', 'e', 'e']

6、 join

join(iterable)

拼接可迭代对象中的字符串形成一个新的字符串。可迭代对象中不可以出现非字符串,不然会报错。

>>> '#'.join(['1','2','3','4'])
'1#2#3#4'
>>> '#'.join(['1','2','3',4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 3: expected str instance, int found

7、 replace

replace(old, new[, count])

用新字符串代替原有字符串,默认替换所有,count参数可以指定替换次数。

>>> 'hello, world'.replace('o', '#')
'hell#, w#rld'
>>> 'hello, world'.replace('o', '#', 1)
'hell#, world'

8、 isdigit

如果字符串至少有一个字符,且所有字符都是数字,则返回真,否则返回假。

>>> '1234'.isdigit()
True
>>> 'ab1'.isdigit()
False

相对次要的字符串方法

1、find, rfind, index, rindex, count

find和rfind方法是在原字符串中查找指定字符串第一次出现的位置,未找到会返回-1。

index和rindex方法和find方法一样,与find不同的是,找不到会抛异常。

count方法返回字符串在原字符串中出现的次数。

此外,以上5个方法都可以指定start, end参数,相当于对原字符串切片再寻找。

>>> 'hello, world'.find('llo')
2
>>> 'hello, world'.find('z')
-1
>>> 'hello, world'.rfind('l', 4, -1)
10
>>> 'hello, world'.index('z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> 'hello, world'.count('o')
2

2、center, ljust, rjust, zfill

center(width[, fillchar])

返回长度为width的以fillchar填充的字符串。

center是居中对齐,ljust是左对齐,rjust是右对齐,zfill返回长度为width的以0填充的字符串。

>>> 'hello'.center(20, '#')
'#######hello########'
>>> 'hello'.ljust(20, '#')
'hello###############'
>>> 'hello'.rjust(20, '#')
'###############hello'
>>> '4'.zfill(4)
'0004'

3、expandtabs

 将制表符替换为指定数量的空格。

>>> 'abc\t'.expandtabs(12)
'abc         '

4、capitalize, swapcase, title

 这三个方法分别返回首字母大写,原字符串大小写反转,每个单词首字母大写的新字符串。

>>> 'hello, world'.capitalize()
'Hello, world'
>>> 'hello, World'.swapcase()
'HELLO, wORLD'
>>> 'hello, World'.title()
'Hello, World'

4. list

4.1 定义

列表是一个可变类型,数据可以随意存储和修改。

list([iterable])

接受一个可迭代对象,返回列表,无参数时返回空列表。

>>> list('abc')
['a', 'b', 'c']
>>> list()
[]
>>> list(range(4))
[0, 1, 2, 3]

4.2  list主要方法

添加元素

append(x): 在列表末尾添加一个新元素

insert(index, obj):  在列表的指定位置添加一个新元素

extend(iterable): 在列表末尾添加多个元素

>>> l = [1, 2, 3]
>>> l.append(4)
>>> l.append(5)
>>> l
[1, 2, 3, 4, 5]
>>> l.insert(-1, 0)
>>> l
[1, 2, 3, 4, 0, 5]
>>> l.extend([11, 22,])
>>> l
[1, 2, 3, 4, 0, 5, 11, 22]

删除元素

pop(index): 弹出列表指定位置的元素,默认弹出最后一个元素。

del 直接删除列表某个元素

remove(obj): 删除列表的某个元素,无返回值。

>>> l = [1, 2, 3, 4, 5]
>>> l.pop()
5
>>> l.pop(0)
1
>>> l
[2, 3, 4]
>>> del l[1]
>>> l
[2, 4]
>>> l.remove(2)
>>> l
[4]

5. 列表与字符串的共同操作

列表和字符串都是序列,都可以根据索引取值,可以通过len方法获取元素个数,还可以进行切片操作。

按索引取值

>>> s = 'abcde'
>>> s[1]
'b'
>>> l = [1, 2, 3, 4, 5]
>>> l[3]
4

获取长度

>>> len('abc')
3
>>> len([1, 3, 5, 7])
4

切片

>>> s = 'abcdefg'
>>> s[1:5]      # 获取索引1到4的元素
'bcde'
>>> s[-1: 1: -1]   # 获取最后一个元素到第二个元素的切片
'gfedc'
>>> s[::-1]    # 反转
'gfedcba'
>>> s[:-1:2]   # 获取步长为2的切片
'ace'

  

 

posted @ 2019-07-03 16:30  yscl  阅读(229)  评论(0)    收藏  举报