在python中,str对象处理文本或字符串类型的数据。字符串是不可变的。字符串是Unicode字符序列。我们可以使用单引号,双引号或三引号来定义字符串文字。
“这是带单引号的字符串”
“另一个带双引号的文本”
'''使用三个单引号的文本'''或“”“使用三个双引号的文本”“”
我们可以使用三引号在python中分配多行字符串。
有不同的字符串相关功能。一些String方法如下-
| 序号 | 操作/功能和说明 |
|---|---|
| 1 | s.capitalize() 将第一个字符转换为大写字母 |
| 2 | s.center(width [,fillchar]) 具有指定字符的填充字符串。默认值为''<space> |
| 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(可迭代) 连接字符串 |
| 11 | s.ljust(width [,fillchar]) 返回左对齐字符串 |
| 12 | s.rjust(width [,fillchar]) 返回正确的对齐字符串 |
| 13 | 慢点() 转换为小写字母 |
| 14 | s.split(sep =无,maxsplit = -1) 用给定的分隔符分割字符串 |
| 15 | s.strip([字符]) 从字符串中切出字符 |
| 16 | s.swapcase() 将小写转换为大写,反之亦然 |
| 17 | 晚餐() 转换为大写字母 |
| 18岁 | s.zfill(宽度) 通过添加零来转换字符串。 |
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