python学习(有始有终)第1章 变量、名字和对象

第1章

1.1 变量、名字和对象

  • type(thing) 获取对象的类型
a = 12
type(a)
<class'int'>
  • 变量名可包含的字符和规则
    • 小写字母(a~z)
    • 数字(0~9)
    • 下划线(_)
    • 名字不允许以数字开头
    • 不允许使用python保留的关键字

1.2 数字

运算符 描述 示例
+ 加法 5+8=13
- 减法 90-10=80
* 乘法 4*7=28
/ 浮点数除法 7/2=3.5
// 整数除法 7//2=3
% 模(求余) 7%3=1
** 3**4=81

1.2.1 整数

  • 运算等价关系
# +、-、*、/、//、**
a = 100
a = a - 3 等价 a -= 3

1.2.2 基数

  • 进制
    • 0b 或 0B代表二进制
    • 0o 或 0O代表八进制
    • 0x 或 0X代表十六进制

1.3 字符串

  • 引号使用
    • 双引号和单引号嵌套—>使字符串包含引号
    • 三引号—>输入输出多行字符串
  • 使用\转义
    • \n换行
    • \t制表符
    • \"显示引号
    • \\显示单斜杠
  • 拼接操作
    • 使用+拼接
    • 使用*复制
    • 使用[]提取字符
>>>letter = 'you are, you are'
>>>letter[-1]
'e'
  • 使用[start: end :step]分片
    • [:]
    • [start:]
    • [:end] 从开头提取到end-1
    • [start:end] 从开头到end-1
    • [start: end :step]
    • 偏移量从左至右从0、1开始,依次增加
    • 从右至左从-1、-2开始,依次减小
  • 使用len()获得长度
    • 也可以对其他序列类型使用len()
  • 使用split()分割 string.function(argumens)
    • 内置字符串函数split()可以基于分隔符将字符串分割成由若干子串组成的列表
>>>a = 'you are , you are beautiful.'
>>>a.split(',')
['you are','you are beautiful.']
  • 使用join() 合并string.join(list)
    • join()函数将包含若干子串的列表分解,并将这些子串合成一个完整的大的字符串
>>>str_list = ['you are','you are beautiful.']
>>>str_list2 = ','.join(str_list)
>>>print(str_list2)
you are, you are beautiful.
  • 常用字符串函数
    • a.startswith(‘all’) —>判断字符串a是不是以all开头
    • a.endswith(‘all’) —>判断a是不是以all结尾
    • a.find(‘all’) —>查找a中第一次出现单词all的位置(偏移量)
    • a.rfind(‘all’) —>最后一次出现all的偏移量
    • a.count(‘all’) —>a中all出现了多少次
    • a.isalnum() —>判断a中是否所有字符都是字母或数字
  • 使用replace()替换
    • replace()进行简单子串替换(需要被替换的子串,用于替换的新子串,以及需要替换多少处)最后一个参数如果省略则默认只替换第一次出现的位置
>>>setup.replace('duck','marmoset')
'a marmoset goes into a bar...'
#修改最多100处
>>>setup.repalce('a ','a famous',100)
'a famous duck goes into a famous bar...'
  • 不常用字符串函数(大小写与对齐方式)
>>>setup = 'a duck goes into a bar...'
#将字符串收尾的.都删除
>>>setup.strip('.')
'a duck goes into a bar'
#让字符串首字母变成大写
>>>setup.capitalize()
'A duck goes into a bar...'
#让所有单词开头字母都变成大写
>>>setup.title()
'A Duck Goes Into A Bar...'
#让所有字母都转换为大写
>>>setup.upper()
'A DUCK GOES INTO A BAR...'
#将所有字母转换为小写
>>>setup.lower()
'a duck goes into a bar...'
#将所有字母的大小写转换
>>>setup.swapcase()
'a DUCK GOES INTO A BAR...'
#假设setup字符串被排版在指定长度(这里是30个字符)的空间里
#在30个字符位居中
>>>setup.center(30)
'  a duck goes into a bar...  '
#左对齐
>>>setup.ljust(30)
'a duck goes into a bar...  '
#右对齐
>>>setup.rjust(30)
'  a duck goes into a bar...'

猜你喜欢

转载自blog.csdn.net/Han_Panda/article/details/111301155