差别
这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录 前一修订版 后一修订版 | 前一修订版 | ||
blog:python:string [2022/07/24 08:33] – caodan | blog:python:string [2023/05/19 20:21] (当前版本) – [字符串截取操作] caodan | ||
---|---|---|---|
行 1: | 行 1: | ||
# 字符串 | # 字符串 | ||
+ | 用单引号`'' | ||
+ | |||
+ | 如果字符串中既包含`' | ||
+ | |||
+ | 例如: `str=" | ||
## 字符串截取操作 | ## 字符串截取操作 | ||
`str=' | `str=' | ||
- | | 命令 | + | | syntax |
- | | `print(str[1:])` | + | | `str[0] ` |
- | | `print(str[:-1])` | abcdef | + | | `str[5] ` |
- | | `print(str[-1:])` | g | `[-1: | + | | `str[-1] ` |
- | | `print(str[::-1])` | gfedcba | + | | `str[-2] ` | f | the second last character |
- | | `print(str[::-2])` | geca | `[::-2]` 字符串逆序,间隔一个字符 | + | | `str[0:2] ` | ab | characters from position 0(include) to position 2(exclude) |
- | | `print(str[:])` | abcdefg | + | | `str[2:5] ` | cde | characters from position 2(include) to position 5(exclude) |
+ | | `str[:2] ` | ab | characters from the beginning to position 2(exclude) | ||
+ | | `str[: | ||
+ | | `str[4:] ` | efg | characters from position 4 to the end | | ||
+ | | `str[-2:] ` | fg | characters from the second last to the end | ||
+ | | `str[-1:] ` | f | the last character | ||
+ | | `str[:]` | abcdefg | ||
+ | | `str[::-1]` | gfedcba | ||
+ | | `str[::-2]` | geca | `[::-2]` 字符串逆序,间隔一个字符 | ||
+ | |||
+ | ## ord & chr | ||
+ | |||
+ | ord将字符转换为对应的ASCII码 | ||
+ | |||
+ | chr 将0-255的任一整数转换为对应的字符 | ||
+ | |||
+ | ## join | ||
+ | |||
+ | string.join(iterable) | ||
+ | |||
+ | 将多个字符串连接, | ||
+ | |||
+ | 例: | ||
+ | |||
+ | ``` | ||
+ | str1 = ' | ||
+ | str2 = ' | ||
+ | ' | ||
+ | ``` | ||
+ | |||
+ | 结果为: | ||
+ | |||
+ | ``` | ||
+ | ' | ||
+ | ``` | ||
+ | |||
+ | 结果为: | ||
+ | 字符串的链接符号即调用join的字符串 | ||