百度飞桨领航团零基础Python速成营 课节2: Python编程基础

课节2: Python编程基础
https://aistudio.baidu.com/aistudio/course/introduce/7073
一、字符串
1、字符串定义与遍历
for i in str:
print(i)
2、字符串索引、切片
正向索引,负向索引
切片的语法:[起始:结束:步长] 字符串[start: end: step] 这三个参数都有默认值,默认截取方向是从左往右的 start:默认值为0; end : 默认值未字符串结尾元素; step : 默认值为1;
如果切片步长是负值,截取方向则是从右往左的

3、字符串常用函数
count 计数功能
显示自定字符在字符串当中的个数
find 查找功能
返回从左第一个指定字符的索引,找不到返回-1
index 查找
返回从左第一个指定字符的索引,找不到报错
split 字符串的拆分
按照指定的内容进行分割
字符串标准化
默认去除两边的空格、换行符之类的,去除内容可以指定
4、字符串的格式化输出
%
format
一种可读性更好的方法 f-string
** python3.6版本新加入的形式

二、list进阶
1、list的定义 []
2、list索引、切片,同string,同为序列类型
3、list常用函数
添加新的元素 append 添加一个元素 insert extend
4、count 计数 和 index查找
5、删除元素 pop remove
6、列表生成式
Question1: 列表每一项+1

pythonic的方法 完全等效但是非常简洁
[n+1 for n in list_1]
Question2: 列表中的每一个偶数项[过滤]

小练习:0-29之间的奇数
list_1 = range(30)
[e for e in list_1 if e % 2 == 1]

#小练习 在list_A 但是不在list_B中
list_A = [1,3,6,7,32,65,12]
list_B = [2,6,3,5,12]
[i for i in list_A if i not in list_B]

7、生成器
# 第一种方法:类似列表生成式
L = [x * x for x in range(10)]
g = (x * x for x in range(10))
next(g)
for n in g:
print(n)

第二种方法:基于函数

练习 斐波那契数列

def feb(max_num):
n_1 = 1
n_2 = 1
n = 0
while n if n == 0 or n == 1:
yield 1
n += 1
else:
yield n_1 + n_2
new_n_2 = n_1
n_1 = n_1 + n_2
n_2 = new_n_2
n += 1

g = feb(20)
for n in g:
print(n)

你可能感兴趣的:(python)