写在最前面
因为种种原因,喜提史上最长寒假。
在家闲来无事,同时因为项目需要用到python相关内容(其实是keras,没现成的代码,自己改又不会改),所以打算开始学习python。
这个系列算是笔记,详细的学习内容请大家移步骆昊老师的GitHub。
Python - 100天从新手到大师
字符串和常用的数据结构
这部分来源教程day 07,python中有很多关于字符串的方法,需要用到的时候查即可。
字符串
#可用‘’或“”
s1 = 'hello ' * 3
print(s1) # hello hello hello
可用in 和 not in 判断一个字符串是否包含另一个字符串
s2 = 'world'
s1 += s2
print(s1) # hello hello hello world
print('ll' in s1) # True
print('good' in s1) # False
从字符串中取出字符
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
各种方法
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('!')