python笔记-变量与字符串

一、变量

变量: 用于存放程序运行过程中要使用的中间值.

1.1 变量命名规则

  1. 由字母、数字、下划线组成
  2. 不能由数字开头
  3. 不能是python关键字和内置函数

1.2 python命名规范

1.2.1 驼峰式命名规范

单词之间使用单词的首字母进行大写用于区分.

  1. 大驼峰
    • 每个单词的首字母的要大写
    • 例如: MyName, HelloWorld...等称为大驼峰命名规范
  2. 小驼峰
    • 第一个单词的首字母小写, 其余单词首字母大写
    • 例如: getUrl, getInfo...等称为小驼峰

1.2.2 下划线分隔方式

单词与单词之间使用下划线分隔开

例如: get_info, num...等

pep8推荐的变量命名规范

1.2 各个类型变量的定义

  • 整型变量的定义
    * 变量名 = 整数
  • 浮点型变脸的定义
    * 变量名 = 浮点数
  • 字符串变量的定义
    * 变量名 = 字符串

1.3 python变量的本质

可以将python变量理解为一张标签贴纸。 不论哪个类型都可以将这个变量名贴到数据类型上. 就如同C语言的void指针.

在之前,介绍的python对象存在基本的三要术: 标识(id), 类型(type), 值(value).

python变量存放的值, 实际上就是对象标识(id). 在CPython解释器中, id就是对象的内存地址.

二、字符串

  • 由单引号('...')或双引号("...")或三引号("""..."""'''...''')引起来的字符称为字符串
  • 特征
    * 有序性: 称字符串为序列类型. python支持还其他序列类型, 例如: 列表(list), 元组(tuple)
    * 序列类型中的每个元素是可以随机访问的. 也即是通过索引(下标)访问.
    * 不可变: 成字符串为不可变类型. 元组也是不可变类型.

2.1 新建一个字符串对象

>>> "hello"
'hello'
>>> "你好"
'你好'
>>> 'world'
'world'
>>> """python
... hello"""
'python
hello'

2.2 字符串对象的常用操作

字符串是不可变对象. 涉及到字符串字面值修改的操作均是返回一个新的字符串对象

  1. 字符串拼接
    • 操作符(+): 用于连接两个字符串
    • 操作符(*): 用于重复n次字符串
    • 相邻的字面值字符串, 可以被解释器自动拼接在一起
>>> "hello "
'hello '
>>> _ + "world"  # _内置变量, 用于保存最近一次输出的值. 不建议对其进行赋值
'hello world'
>>> "py" "thon"  # 自由字面值才可以, 变量和字面值是不可以自动拼接, 必须使用 + 进行拼接
'python'
>>> "hel" * 3
'helhelhel'
>>> "hel " * 3
'hel hel hel '
>>> py = "py"
>>> th = "thon"
>>> py + th
'python'
>>>
  1. 索引取值
    • 索引也即下标, 一般从左到右以0开始计数. 在python中, 可以从右到左进行编号, 从-1开始
    • 字符串[index]: index即是下标
>>> "python"[1]
'y'
>>> "python"[-1]
'n'
>>> "python"[0]
'p'
>>> "python"[6]  # 超出索引就会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> "python"[5]  # 索引最长为 字符串长度-1
'n'
  1. 切片
    • 所谓切片即是从字符串中获取一段子字符串.
    • 字符串[start: stop[: step]]:
      * start: 为开始位置下标, 会被取到子字符串中.
      * stop: 结束位置下标, 不会被取到子字符串中.
      * step: 步长, 每隔 step-1个位置取一个值到子字符串
>>> "python"[0:3]
'pyt'
>>> "python"[:3]
'pyt'
>>> "python"[2:5]
'tho'
>>> "python"[3:]
'hon'
>>> "python"[1:5:2]
'yh'
  1. 拆包
    • 所谓拆包即是将序列类型的每一个元素值都赋值给一个变量
    • 变量0, 变量1, 变量2, ..., 变量n-1 = 长度为n的字符串: 将每个字符赋值到对应位置变量
    • 变量0, 变量1,...,变量i-1 *变量 = 长度为n的字符串: 将字符串的前i个字符分别赋值到对应位置变量. 其余字符打包成列表赋值給*后的变量
>>> p,y,t,h,o,n = "python"
>>> p
'p'
>>> y
'y'
>>> t
't'
>>> h
'h'
>>> o
'o'
>>> n
'n'
>>> p, y, *th = "python"
>>> p
'p'
>>> y
'y'
>>> th
['t', 'h', 'o', 'n']
  1. 测试字符串长度
    • len(字符串): 返回字符串的长度
    • len(iter): 内置函数, 返回iter的长度
>>> len("hello world")
11
  1. 大写首字母(str.capitalize())
    一个句子的首字母
>>> "hello world".capitalize()
'Hello world'
  1. 清除大小写(str.casefold())
>>> "Hello".casefold()
'hello'
  1. 字符串居中(str.center(width, fliichar=" "))
>>> "hello".center(20)
'       hello        '
>>> "hello".center(20, "*")
'*******hello********'
  1. 子字符串重复次数统计(count(sub[, start[, end]]))
>>> "hello".count("l")
2
>>> "hello".count("ll")
1
>>> "hello".count("ll", -1, -4)
0
>>> "hello".count("ll", 2, 4)
1
  1. 字符串编码字节(str.encode(encoding="utf-8", errors="strict"))
    返回字符的指定字符集的字节编码
>>> "hello".encode()
b'hello'
  1. 判断字符串是否以某个字符串结束(str.endswith(suffix[, start[, end]]))
>>> "hello".endswith("o")
True
>>> "hello".endswith("lo")
True
>>> "hello".endswith("l")
False
>>> "hello".endswith("l", -2, -5)  # 指定判断区间
False
>>> "hello".endswith("l", -5, -2)
True
  1. 查询子字符串在字符串中的位置(最小: str.find(sub[, start[, end]), 最大: str.rfind(sub[, start[, end]))
>>> "hello".find("l")  # 存在返回子字符串的索引
2
>>> "hello".find("w")  # 不存在返回 -1
-1
>>> "hello".find("ll")
2
>>> "hello".find("ll", 1,4)
2
>>> "hello".rfind("l")
3
  1. 查询子字符串在字符串中的位置(最小: str.index(sub[, start[, end]]), 最大: str.rindex(sub[, start[, end]]))
    与str.find()类似. 但是如果查询的子字符串不存在则会报错
>>> "hello".index("l")
2
>>> "hello".index("ll")
2
>>> "hello".index("w")  # 不存在会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> "hello".rindex("l")
3
  1. 添加子字符串到字符串(str.join(iterable))
    将可迭代对象iterable中的字符添加到字符串中. iterable中的元素只能是字符串.
>>> ",".join("hello")
'h,e,l,l,o'
>>> ",".join(["h", "e", "l","l" ,"o"])
'h,e,l,l,o'
  1. 左右对齐(左对齐: str.ljust(width[, fillchar]), 右对齐: str.rjust(width[, fillchar]))
>>> "hello".ljust(10)  # 左对齐
'hello     '
>>> "hello".ljust(10, "*")
'hello*****'
>>> "hello".rjust(10)  # 右对齐
'     hello'
>>> "hello".rjust(10, "*")
'*****hello'
  1. 字母大小写(小写: str.lower(), 大写: str.upper())
>>> "hello".upper()
'HELLO'
>>> "HELLO".lower()
'hello'
  1. 字符串首尾处理(首尾: str.strip([chars]), 首: str.lstrip([chars]), 尾: str.rstrip([chars]))
>>> "    hello   ".strip()  # chars默认是去除空格
'hello'
>>> " .com   hello  .com ".strip(" .com")  # 迭代从chars中
'hell'
>>> "    hello   ".lstrip()
'hello   '
>>> "    hello   ".rstrip()
'    hello'
>>> " .com   hello  .com ".lstrip(" .com")
'hello  .com '
>>> " .com   hello  .com ".rstrip(" .com")
' .com   hell'
  1. 分割字符串(首次: str.partition(sep), 最后: str.rpartition(sep))
>>> "hello".partition("l")
('he', 'l', 'lo')
>>> "hello".partition("e")
('h', 'e', 'llo')
>>> "hello".partition("w")  # sep不在字符串中
('hello', '', '')
>>> "hello".rpartition("l")
('hel', 'l', 'o')
  1. 子字符串替换(str.replace(old, new[, count]))
>>> "hello".replace("l", "r")  # 默认count完全替换
'herro'
>>> "hello".replace("l", "r", 1)  # 指定替换次数, 从左到右
'herlo'
  1. 字符串切割(str.split(sep=None, maxsplit=-1))
>>> "hello".split("l", 1)
['he', 'lo']
>>> "hello".split("l")
['he', '', 'o']
>>> "hello".rsplit("l", 1)
['hel', 'o']
  1. 标题化字符串(str.title())
>>> "love python".title()
'Love Python'

2.3 字符串格式化

2.3.1 printf风格格式化

  1. 基本语法格式: format_string % values
    • format_string: 要被填充的字符串.
      * format_string: "%填充符"
    • values: 要填充到format_string的值. 如果format_string只有一个填充位置, 则values可以不是元组. 如果format_string要填充两个及以上的位置, 则values是元组.
    • 格式如下:"%[(name)][flags][width].[precision]typecode"
      * (name): 通过关键字填充时使用, 字典映射
      * flags: 取值为 +,-,'空格' ,0;
      * + 作用为显示插入数字的正负号,
      * - 左对齐
      * '空格'和0为填充符
      * 填充字符的宽度
      * precision: 保留小数点后的位数 注释:插入数据时浮点数时才生效
      * typecode: 转换符
  2. 示例
In [1]: "%s" % "hello world"  # %s: 填充字符串时使用, 在填充可以转为字符串的内容时, 也可以使用
Out[1]: 'hello world'

In [2]: "%(name)s" % {"name": "dyp"}  # 通过字典映射值.
Out[2]: 'dyp'

In [6]: "%f" % 3.14  # %f: 填充浮点数, 默认保留6位小数, 不足用0补齐
Out[6]: '3.140000'

In [7]: "%d" % 10  # %d: 填充整数
Out[7]: '10'

In [8]: "%c" % "h"  # %c: 填充一个字符. ASCII字符才能被填充进去
Out[8]: 'h'

In [18]: "%e" % 300.31  # %e: 指数形式浮点数
Out[18]: '3.003100e+02'

In [19]: "%o" % 10  # 有符号八进制整数
Out[19]: '12'

In [20]: "%x" % 10  # 有符号十六进制整数
Out[20]: 'a'

In [21]: "%#x" % 10  # 井号(#), 八进制, 填充0o, 十六进制填充0x
Out[21]: '0xa'

In [22]: "%#o" % 10
Out[22]: '0o12'

In [23]: "%5d" % 10  # 5, 指定格式化的宽度. 及总共格式5个字符
Out[23]: '   10'

In [24]: "%05d" % 10  # 5前面的0, 使用0填充整个格式字符串到5. 只有右对齐时, 0填充符才会生效
Out[24]: '00010'

In [25]: "%-5d" % 10  # -, 表示左对齐
Out[25]: '10   '

In [28]: "%+5d" % 10  # +, 显示数的正负号.
Out[28]: '  +10'

In [29]: "%(name)s: %(age)d" % {"name": "dyp", "age": 22}  # 关键字映射格式
Out[29]: 'dyp: 22'

2.3.2 format()方法格式化

使用{}在字符中进行占位. 在使用format()方法对占位进行填充

"{[index|arguments]:[fill][alignment][width].[precision][typecod]}"

  • [index|arguments]: index, 在format参数表中的索引. arguments, format参数表中键值
    * index索引映射 arguments参数映射
    * 默认按位置, 在format参数列表中取值
  • fill: 填充符 (可选, 默认空格)
  • alignment: 对齐方式 < > ^ (可选, 默认右对齐)
    * <: 左对齐
    * >: 右对齐
    * ^: 居中对齐
  • 格式化宽带(可选)
  • precision: 保留小数点后的位数 注释:插入数据时浮点数时才生效(可选)
  • typecod: 转换符. (可选)
In [37]: "{}'s age is {}".format("Array", 10)  # 正常按位置填充
Out[37]: "Array's age is 10"

In [38]: "{2}'s age is {1}".format("Array", 10, "Marry")  # 指定位置填充
Out[38]: "Marry's age is 10"

In [39]: "{name}'s age is {age}".format("Mary", name="Array", age=10)  # 关键值填充
Out[39]: "Array's age is 10"

In [40]: "{name}'s age is {age:f}".format("Mary", name="Array", age=10)  # 可以指定格式化数据的类型
Out[40]: "Array's age is 10.000000"

In [41]: "{name}'s age is {age:d}".format("Mary", name="Array", age=10)
Out[41]: "Array's age is 10"

In [42]: "{:#b}".format(10)  # 对进制进行格式. 二进制
Out[42]: '0b1010'

In [43]: "{:b}".format(10)
Out[43]: '1010'

In [44]: "{:o}".format(10)  # 八进制
Out[44]: '12'

In [45]: "{:#o}".format(10)
Out[45]: '0o12'

In [46]: "{:x}".format(10)  # 十六进制
Out[46]: 'a'

In [47]: "{:#x}".format(10)
Out[47]: '0xa'

In [57]: "{:5d}".format(10)  # 宽度指定
Out[57]: '   10'

In [58]: "{:05d}".format(10)  # 填充符指定
Out[58]: '00010'

In [59]: "{:0<5d}".format(10) # 对齐方式指定. 默认右对齐
Out[59]: '10000'

In [60]: "{:5f}".format(3.14)
Out[60]: '3.140000'

In [61]: "{:5.2f}".format(3.14)
Out[61]: ' 3.14'

In [62]: "{:05.2f}".format(3.14)
Out[62]: '03.14'

In [63]: "{:0<5.2f}".format(3.14)
Out[63]: '3.140'

2.3.3 f"{}"字符串格式化

python3.6增加的功能. 类似与format_strinf.format()

f"{variable:[fill][alignment][width].[precision][typecod]}"

  • variable: 要填充的值
  • fill: 填充符 (可选, 默认空格)
  • alignment: 对齐方式 < > ^ (可选, 默认右对齐)
    * <: 左对齐
    * >: 右对齐
    * ^: 居中对齐
  • 格式化宽带(可选)
  • precision: 保留小数点后的位数 注释:插入数据时浮点数时才生效(可选)
  • typecod: 转换符. (可选)
In [68]: string = "hello world"

In [69]: f"{string}"  # 正常使用
Out[69]: 'hello world'

In [71]: f"{string:20}"  # 20: 指定宽度
Out[71]: 'hello world         '

In [72]: f"{string:>20}"  # >: 指定对齐方式. 默认左对齐
Out[72]: '         hello world'

In [73]: f"{string:0>20}"  # 0: 指定的填充符
Out[73]: '000000000hello world'

In [77]: f"{string:0^20s}"  # s: 指定的格式对象的类型.
Out[77]: '0000hello world00000'

In [78]: f"{10:b}"  # 数进制格式, 二进制
Out[78]: '1010'

In [79]: f"{10:#b}"
Out[79]: '0b1010'

In [80]: f"{10:o}"  # 八进制
Out[80]: '12'

In [81]: f"{10:#o}"
Out[81]: '0o12'

In [82]: f"{10:x}"  # 十六进制
Out[82]: 'a'

In [83]: f"{10:#x}"
Out[83]: '0xa'
原文地址:https://www.cnblogs.com/duyupeng/p/13045257.html