【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
字符串和常用数据结构
单引号和双引号,正常输出 三引号,中间可以换行输出 \转义 前面加上 r 表示不加以转义
s1 = r'\'hello, world!\''
s2 = r'\n\\hello, world!\\\n'
print(s1, s2, end='')
str1 = 'hello, world!'
# 通过内置函数len计算字符串的长度
print(len(str1)) # 13
# 获得字符串首字母大写的拷贝
print(str1.capitalize()) # Hello, world!
# 获得字符串每个单词首字母大写的拷贝
print(str1.title()) # Hello, World!
# 获得字符串变大写后的拷贝
print(str1.upper()) # HELLO, WORLD!
# 从字符串中查找子串所在位置
print(str1.find('or')) # 8
print(str1.find('shit')) # -1
# 与find类似但找不到子串时会引发异常
# print(str1.index('or'))
# print(str1.index('shit'))
# 检查字符串是否以指定的字符串开头
print(str1.startswith('He')) # False
print(str1.startswith('hel')) # True
# 检查字符串是否以指定的字符串结尾
print(str1.endswith('!')) # True
# 将字符串以指定的宽度居中并在两侧填充指定的字符
print(str1.center(50, '*'))
# 将字符串以指定的宽度靠右放置左侧填充指定的字符
print(str1.rjust(50, ' '))
str2 = 'abc123456'
# 检查字符串是否由数字构成
print(str2.isdigit()) # False
# 检查字符串是否以字母构成
print(str2.isalpha()) # False
# 检查字符串是否以数字和字母构成
print(str2.isalnum()) # True
str3 = ' jackfrued@126.com '
print(str3)
# 获得字符串修剪左右两侧空格之后的拷贝
print(str3.strip())
切片
str2 = 'abc123456'
print(str2[2]) # c
print(str2[2:5]) # c12
print(str2[2:]) # c123456
print(str2[2::2]) # c246
print(str2[::2]) # ac246
print(str2[::-1]) # 654321cba
print(str2[-3:-1]) # 45
列表
列表中查找元素
[root@jenkins python]# python3
Python 3.7.3 (default, Dec 6 2019, 23:40:50)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [1, 3, 5, 6, 100]
>>> print(list1)
[1, 3, 5, 6, 100]
>>> print(len(list1))
5
>>> print(list1)
[1, 3, 5, 6, 100]
>>> print(list1[-1])
100
>>> print(list1[1])
3
>>> print(list1[3])
6
对元素遍历
[root@jenkins python]# python 2.py
1
3
5
7
100
1
3
5
7
100
(0, 1)
(1, 3)
(2, 5)
(3, 7)
(4, 100)
[root@jenkins python]# cat 2.py
list1 = [1, 3, 5, 7, 100]
for index in range(len(list1)):
print(list1[index])
for elem in list1:
print(elem)
for index, elem in enumerate(list1):
print(index, elem)
列表中新增和减少元素
list1 = [1, 3, 5, 7, 100]
新增:
list1.append(2 )
list1.insert(1, 6)
合并:
list1.extend([11, 222])
减少:
如果3在列表中则移除
if 3 in list1:
list1.remove(3)
指定位置删除
list1.pop(0)
清空
list1.clear()
元组
元组的元素不能修改,一个不变的对象要比可变的对象更加容易维护
tup2 = (1, 2, 3, 4, 5 )
字典
dict = {'a': 1, 'b': 2, 'b': '3'}
三者的区别是什么呢? 相信仔细对比,大家可以看得出来 参考文档:https://github.com/jackfrued/Python-100-Days
来源:oschina
链接:https://my.oschina.net/u/3635512/blog/3143762