Python 文本序列类型
在 Python 中,str 对象处理文本或字符串类型数据。字符串是不可变的。字符串是 Unicode 字符的序列。我们可以使用单引号、双引号或三引号来定义字符串字面量。
- ‘这是一个用单引号括起来的字符串’
- “另一个用双引号括起来的文本”
- ‘’’使用三个单引号的文本’’’ 或 “””使用三个双引号的文本”””
我们可以使用三引号在 Python 中赋值多行字符串。
有不同的与字符串相关的函数。一些字符串方法如下:
| 序号 | 操作/函数和描述 |
|---|---|
| 1 | s.capitalize() 将第一个字符转换为大写字母 |
| 2 | s.center(width[, fillchar]) 用指定字符填充字符串。默认为 ' ' <空格> |
| 3 | s.count(sub[, start[, end]]) 计算字符串中出现的次数 |
| 4 | s.find(sub[, start[, end]]) 返回文本中子字符串的第一次出现位置 |
| 5 | s.format(*args, **kwargs) 格式化字符串以生成良好的输出 |
| 6 | s.isalnum() 检查字母数字字符 |
| 7 | s.isalpha() 检查所有字符是否都是字母 |
| 8 | s.isdigit() 检查数字字符 |
| 9 | s.isspace() 检查字符串中的空格 |
| 10 | s.join(iterable) 连接字符串 |
| 11 | s.ljust(width[, fillchar]) 返回左对齐的字符串 |
| 12 | s.rjust(width[, fillchar]) 返回右对齐的字符串 |
| 13 | s.lower() 转换为小写字母 |
| 14 | s.split(sep=None, maxsplit=-1) 用给定的分隔符分割字符串 |
| 15 | s.strip([chars]) 从字符串中剪切字符 |
| 16 | s.swapcase() 将小写转换为大写,反之亦然 |
| 17 |
s.upper() 转换为大写字母 |
| 18 | s.zfill(width) 通过在其前面添加零来转换字符串。 |
示例代码
myStr1 = 'This is a Python String'
myStr2 = "hello world"
print(myStr2)
print(myStr2.capitalize())
print(myStr2.center(len(myStr1)))
print(myStr1)
print(myStr1.find('Py')) #The location of substring Py.
myStr3 = 'abc123'
print(myStr3.isalnum())
print(myStr3.isdigit())
print('AB'.join('XY'))
print(myStr2.rjust(20, '_')) #Right justified string, filled with '_' character
print(myStr1.swapcase())
print('2509'.zfill(10)) #Fill 0s to make 10 character long string
输出
hello world
Hello world
hello world
This is a Python String
10
True
False
XABY
_________hello world
tHIS IS A pYTHON sTRING
0000002509
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP