变量、数据类型
变量: 为什么要有变量
首先,变量是一个容器,存放值的一个容器,可以将任意值存放在这个容器里。
变量作用:保存状态,(程序的运行本质是一系列状态的变化,变量的目的就是用来何足保存状态,变量值的变化就构成了程序运行的不同结果。)
变量解决的问题:
1、可以重用
2、方便调用
变量的命名规则:
- 避免与python 内置的方法 重名,如append list ……..
- name=’tony’ tony 是内存变量 ,name 只是内存变量的引用
数据类型:
数据类型分类:例如人有名字 ,年龄 ,身高
名字:------>字符串”tony”
年龄: -------> 数字 12
职业:---------> 列表 [‘教师’,’司机’ ]
上述的类型可以分为:
标准类型 | 其他类型 |
数字 | 类型type |
字符串 | Null |
列表 | 文件 |
元组 | 集合 |
字典 | 函数 /方法 |
bool | 类 |
模块 |
字符串的使用方法:
#strip的使用
>>> a=' hello tony '
>>> a.strip() #去掉前后的空格
'hello tony'
>>>
>>> a.strip(' h') #去掉空格加’h’ 字母
'ello tony'
>>> a.rstrip('o ') #右边 o 字母和空格 都去掉
hello tony'
>>>
#str.startswith() #返回布尔值 a='hello tony'>>> a.strip()
'hello tony'
>>> a1.startswith('h')
True
#startwith,endswith
>>> a.endswith('y')
False
>>> a1.endswith('y')
True
字符串格式化:
>>> print("hello {name} ,my name is {name2} ,age {age}".format(name='lili',name2='tony',age=23))
hello lili ,my name is tony ,age 23
print('hello {1} , age is {0}'.format('tony',19))
###split replice join
split #切割字符串
>>> print(s1.split()) #默认为空格 切割 成列表
['welcome', 'tony']
>>> print(s1.split('o')) #输入o 则以o 切割
['welc', 'me t', 'ny']
>>>
replice #字符替换
>>> s1.replace('tony','david')
'welcome david'
>>> s1.replace('o','m')
'welcmme tmny'
>>>
还可以指定替换次数
>>> s1.replace('o','p',1)
'welcpme tony'
>>>
join 用法:
>>> li1 #是一个列表
['david', 'tony', 'john']
>>> ' '.join(li1) # join 成一个字符串
'david tony john'
>>>
>>> ','.join(li1)
'david,tony,john' # 以逗号为分隔,join成一个字符串
>>>
count 统计字符
>>> a='toony' >>> a.count('o') 2
center操作
#默认是空格,加上字符串左边和右边10个空格 >>> a.center(20) ' toony '
加上字符串,左边和右填充-号
>>> a.center(20,'-')
'-------toony--------'
>>>
find 查看字符位置
>>> a.find('o') # ‘o’ 的字符在索引 1的位置 1 >>> a.find('t') # 't' 字符在索引0的位置 0 >>>
index 索引字符位置:
>>> a.index('o') #索引 字符 'o' 的位置 1 >>> a.index('y') 4
isalnum 判断是不是 alphabetical ASCII 的字符串
>>> a='toony 123' # 有字母和数字 >>> a.isalnum() #不是 alphabetical ascii 字符串 False >>> b='tony' >>> b.isalnum() #只有字母 True >>> c='123' #只有数字 >>> c.isalnum() True
isalpha 判断是否是isalpha 字母
>>> c='123' >>> c.isalpha() # 有数字则不是 False >>> b='tony' #只有字符 返回真 >>> b.isalpha() True
isdigit 判断是否是数字
>>> b='tony' #不是数字返回False >>> b.isdigit() False >>> c='123' # 是数字 返回True >>> c.isdigit() True
islower 判断是否小写字母
>>> b='ABC' >>> b.islower() #不是小写字母返回 False False >>> a='tony' #是小写则返回True >>> a.islower() True
>>> a.isupper() #不是大写 返回Fallse False >>> b.isupper() #是大写,返回 True True
maketrans 从开始字符到目标字符的位置, 返回一个字典格式,
>>> a.maketrans('a','z') {97: 122} >>> a.maketrans('a','b') {97: 98} >>> b.maketrans('a','b') {97: 98} >>> b.maketrans('A','D') {65: 68} >>> b.maketrans('1','2') {49: 50}