yyz notes yyz notes
首页
  • RBAC权限设计
  • 架构图标设计
  • 账号体系
  • python基础
  • python高级
  • python模块
  • python设计模式
  • python数据结构与算法
  • django
  • django-DRF
  • flask
  • 直接设计开源pip包
  • 直接设计开源项目
  • python示例题/脚本
  • python面试题
  • golang基础
  • golang高级
  • golang常用组件
  • gin框架
  • es6
  • javascript
  • react
  • vue
  • TypeScript
  • mysql
  • redis
  • minio
  • elasticsearch
  • mongodb
  • 消息队列
  • 自动化测试
  • 操作系统

    • linux
    • windows
  • nginx
  • docker
  • k8s
  • git
  • ldap
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

益章

可乐鸡翅
首页
  • RBAC权限设计
  • 架构图标设计
  • 账号体系
  • python基础
  • python高级
  • python模块
  • python设计模式
  • python数据结构与算法
  • django
  • django-DRF
  • flask
  • 直接设计开源pip包
  • 直接设计开源项目
  • python示例题/脚本
  • python面试题
  • golang基础
  • golang高级
  • golang常用组件
  • gin框架
  • es6
  • javascript
  • react
  • vue
  • TypeScript
  • mysql
  • redis
  • minio
  • elasticsearch
  • mongodb
  • 消息队列
  • 自动化测试
  • 操作系统

    • linux
    • windows
  • nginx
  • docker
  • k8s
  • git
  • ldap
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • python基础

    • python概述

    • python环境搭建

    • python基础语法

      • 变量与常量
      • 基本数据类型-整数类型
      • 基本数据类型-浮点数类型
      • 基本数据类型-复数类型
      • 基本数据类型-布尔类型
      • 基本数据类型-bytes类型
      • 复杂数据类型-序列
      • 复杂数据类型-字符串
        • 链接资料
        • 1. 字符串的创建
        • 2 字符串的转义
        • 3. 字符串的相关方法
        • 4. str() 和 repr() 的区别
        • 5. p*ython 中的 Unicode*
        • 6. *字符串格式化输出*
          • 1. 格式化字符串字面值f
          • 2. 字符串 format() 方法
          • 3. 手动格式化字符串
          • 4. 旧式字符串格式化方法
        • 7. 字符串其他用法
      • 复杂数据类型-列表
      • 复杂数据类型-元组
      • 复杂数据类型-字典
      • 复杂数据类型-集合
      • list,tuple,dict,set的区别和联系
      • 推导式
      • 浅拷贝和深拷贝
      • 运算符
      • 输入输出
    • python关键字与标识符

    • python流程控制

    • python函数

    • python内置函数

    • python面向对象

    • python模块与包

    • python文件IO与OS

    • python异常处理机制

  • python高级

  • python模块

  • python设计模式

  • python数据结构与算法

  • django

  • django-DRF

  • flask

  • 自己设计开源pip包

  • 自己设计开源项目

  • python小示例

  • python面试题

  • python
  • python基础
  • python基础语法
YiZhang-You
2023-05-09
目录

复杂数据类型-字符串

# 链接资料

2.1 使用多个界定符分割字符串 - python3-cookbook 3.0.0 文档 (opens new window)

# 1. 字符串的创建

将文本放在单引号、双引号和三引号之间

str1 = ' hello, fanison '
str1 = " hello, fanison "
str1 = """hello word"""
1
2
3

# 2 字符串的转义

原生字符串:使用r

str1 = r"hello, fanison"
1

# 3. 字符串的相关方法

详细:建议多看文档

Python 字符串方法 (opens new window)

| --- | --- |

注释:所有字符串方法都返回新值。它们不会更改原始字符串。

s.index(sub [,start [,end]]) 找到指定字符串sub首次出现的位置,找不到就报错
s.find(str,beg=0,end=len(string)) 找到字符串sub首次出现位置,与index不同是不报错而返回-1
s.upper() 将一个字符串转换为大写形式
s.lower() 将一个字符串转化为小写形式
s.join(t) 使用s作为分隔符连接序列t中的字符串 s.strip() 将s两边不显示的符号去掉之后返回(lstrip、rstrip)
s.split(t) 获取以字符t将s切割的列表
s.encode() 获取s的指定编码的bytes值
bytes.decode() 获取bytes的对应编码的字符串,在python2中使用decode函数
s.endswith(suffix,beg=0, end=len(string)) 检查中是否以suffix字符串结尾

x = "do you fuck me?"
print(x.index("y"))  # 找不到就报错
print(x.find("z"))  # 找不到就返回-1
print(x.upper())
print(x.lower())
print(x.join("-x"))
print(x.split(" "))
print(x.encode())
print(x.endswith("f"))  # 判断结尾是不是以f
"""
3
-1
DO YOU FUCK ME?
do you fuck me?
-do you fuck me?x
['do', 'you', 'fuck', 'me?']
b'do you fuck me?'
False
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# 4. str() 和 repr() 的区别

str() 和 repr() 函数虽然都可以将数字转换成字符串,但它们之间是有区别的:

  • str() 用于将数据转换成适合人类阅读的字符串形式。
  • repr() 用于将数据转换成适合解释器阅读的字符串形式(Python 表达式的形式),适合在开发和调试阶段使用;如果没有等价的语法,则会发生 SyntaxError 异常。

# 5. p****ython 中的 Unicode****

如果要创建 Unicode 字符串,请在文本开头添加u或U字符。

#!/usr/bin/env python

# unicode.py

text = u'\\u041b\\u0435\\u0432 \\u041d\\u0438\\u043a\\u043e\\u043b\\u0430\\
\\u0435\\u0432\\u0438\\u0447 \\u0422\\u043e\\u043b\\u0441\\u0442\\u043e\\u0439: \\n\\
\\u0410\\u043d\\u043d\\u0430 \\u041a\\u0430\\u0440\\u0435\\u043d\\u0438\\u043d\\u0430'

print(text)
1
2
3
4
5
6
7
8
9

# 6. *字符串格式化输出*

字符串格式化是将各种值动态地放入字符串中。 可以使用%运算符或format()方法实现字符串格式化。

# 1. 格式化字符串字面值f

格式化字符串字面值 (opens new window)(简称为 f-字符串)在字符串前加前缀 f或 F,通过 {expression}表达式,把 Python 表达式的值添加到字符串内。

格式说明符是可选的,写在表达式后面,可以更好地控制格式化值的方式。下例将 pi 舍入到小数点后三位:

**import** **math>>>** print(f'The value of pi is approximately **{**math.pi**:**.3f**}**.')
The value of pi is approximately 3.142.
1
2

在 ':' 后传递整数,为该字段设置最小字符宽度,常用于列对齐:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print(f'{name:10} ==> {phone:10d}')
...
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678
1
2
3
4
5
6
7

还有一些修饰符可以在格式化前转换值。 '!a' 应用 [ascii()](<https://docs.python.org/zh-cn/3/library/functions.html#ascii>) ,'!s' 应用 [str()](<https://docs.python.org/zh-cn/3/library/stdtypes.html#str>),'!r' 应用 [repr()](<https://docs.python.org/zh-cn/3/library/functions.html#repr>):

>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.
1
2
3
4
5

# 2. 字符串 format() 方法

[str.format()](<https://docs.python.org/zh-cn/3/library/stdtypes.html#str.format>) 方法的基本用法如下所示:

print('We are the **{}** who say "**{}**!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
1
2

花括号及之内的字符(称为格式字段)被替换为传递给 [str.format()](<https://docs.python.org/zh-cn/3/library/stdtypes.html#str.format>) 方法的对象。花括号中的数字表示传递给 [str.format()](<https://docs.python.org/zh-cn/3/library/stdtypes.html#str.format>) 方法的对象所在的位置。

**>>>** print('**{0}** and **{1}**'.format('spam', 'eggs'))
spam and eggs
**>>>** print('**{1}** and **{0}**'.format('spam', 'eggs'))
eggs and spam
1
2
3
4

[str.format()](<https://docs.python.org/zh-cn/3/library/stdtypes.html#str.format>) 方法中使用关键字参数名引用值。

**>>>** print('This **{food}** is **{adjective}**.'.format(
**...**       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
1
2
3

位置参数和关键字参数可以任意组合:

**>>>** print('The story of **{0}**, **{1}**, and **{other}**.'.format('Bill', 'Manfred',
**...**                                                    other='Georg'))
The story of Bill, Manfred, and Georg.
1
2
3

如果不想分拆较长的格式字符串,最好按名称引用变量进行格式化,不要按位置。这项操作可以通过传递字典,并用方括号 '[]' 访问键来完成。

**>>>** table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
**>>>** print('Jack: **{0[Jack]:d}**; Sjoerd: **{0[Sjoerd]:d}**; '
**...**       'Dcab: **{0[Dcab]:d}**'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

**>>> for** x **in** range(1, 11):
**...**     print('**{0:2d}** **{1:3d}** **{2:4d}**'.format(x, x*x, x*x*x))
1
2
3
4
5
6
7
8
9
10
11

# 3. 手动格式化字符串

下面是使用手动格式化方式实现的同一个平方和立方的表:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note use of 'end' on previous line
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 4. 旧式字符串格式化方法

>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.
1
2
3

开头的转换说明符对各种类型的数据进行格式化输出,具体请看下表。

转换说明符 解释

# 7. 字符串其他用法

第二章:字符串和文本 — python3-cookbook 3.0.0 文档 (opens new window)

编辑 (opens new window)
上次更新: 2023/05/17, 23:08:21
复杂数据类型-序列
复杂数据类型-列表

← 复杂数据类型-序列 复杂数据类型-列表→

最近更新
01
配置yun源
05-24
02
linux-配置python虚拟环境
05-24
03
linux文件目录管理
05-24
更多文章>
Theme by Vdoing | Copyright © 2023-2023 yizhang | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式