一、变量类型
1.numbers:分整数int和浮点数float
2.String :单引号,双引号和三引号
python的字符串format格式:一般有两种
1)%操作符:
>>> name = 'xiao ming'
>>> age = 20
>>> print('Your name is %s, age is %d' % (name, age))
Your name is xiao ming, age is 20
2).format
>>> print('Your name is {0}, age is {1}'.format(name, age))
Your name is xiao ming, age is 20
注:.format用法:
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
3.布尔值
Python中的布置值,只有True和False两种(一定要注意大小写),布尔值的运算可以用and,or 和not
4.空值
Python的空值是用None表示,None不是0,也不是空字符串,也不是False,它是一个特殊的空值
二、字符串
1.字符串的连接和合并
1)相加:两个字符串可以很方便的通过'+'连接起来
>>> str1 = 'hello'
>>> str2 = 'world'
>>> new_str = str1 + str2
>>> print(new_str)
helloworld
>>> new_str1 = str1 + '-' + str2
>>> print(new_str1)
hello-world
2)合并:用join方法
>>> url = ['www', 'python', 'com']
>>> print('.'.join(url))
www.python.com
2.字符串的切片和相乘
1)相乘:
>>> line = '*' * 30
>>> print(line)
******************************
2)切片:
>>> str1 = 'Monday is a busy day'
>>> print(str1[1])
o
>>> print(str1[0:2])
Mo
>>> print(str1[0:7:2])
Mna
>>> print(str1[-3:])
day
>>> print(str1[::])
Monday is a busy day
3.字符串的分割
1)普通的分割:plit
>>> phone = '400-800-800-1245'
>>> print(phone.split('-'))
['400', '800', '800', '1245']
2)复杂的分割
r表示不转义,分隔符可以是;或者,或者空格后面跟0个多个额外的空格,然后按照这个模式去分割
>>> line = 'hello world; python, I, like, it'
>>> import re
>>> print(re.split(r'[;,s]s', line))
['hello world', ' python', 'I', 'like', ' it']
4.字符串的开头和结尾的处理
比方我们要查一个文件的名字是以什么开头或者什么结尾
>>> filename = 'trace.h'
>>> print(filename.endswith('h'))
True
>>> print(filename.startswith('trace'))
True
5.字符串的查找和匹配
一般查找,我们可以很方便的在长的字符串里面查找子字符串,会返回子字符串所在位置的索引, 若找不到返回-1
>>> title = 'Python can be easy to pick up and powerfullanguages'
>>> print(title.find('pick up'))
22
6.字符串的替换
1)普通的替换//用replace就可以
>>> text = 'Python is an easy to learn, powerful programming language.'
>>> print(text.replace('learn', 'study'))
Python is an easy to study, powerful programming language.
2)复杂的替换//若要处理复杂的或者多个的替换,需要用到re模块的sub函数
>>> students = 'boy 103, girl 105'
>>> print(re.sub(r'd+','100', students))
boy 100, girl 100
7.字符串中去掉一些字符
去除空格//对文本处理的时候比如从文件中读取一行,然后需要去除每一行的两侧的空格,table或者是换行符
>>> line = ' Congratulations,you gussed it. '
>>> print(line.strip())
Congratulations,you gussed it.
相关知识
【Python】基础
基于python实现网络课程秒刷
Mind+Python编程进阶系列课程—06植物监测仪 DF创客社区
python基础语法花多长时间
水彩网络课 | 梦幻花卉系统课程:基础+进阶
python基础作业
Python中的数据可视化:Matplotlib基础与高级技巧
视频教程
第 1 章 机器学习基础引言
花了1个月时间,把Python库全部整理出来了,覆盖所有,建议收藏
网址: python基础课程系列(补充1) https://m.huajiangbk.com/newsview465232.html
上一篇: 鲜花相关文章列表 |
下一篇: 乔叶《鲜花课》 |