Working With Strings In Python.

字符串操作

在Python中,string 是一种不可变的数据类型,用于表示文本或字符序列,可以使用单引号或双引号将字符串括起来。所有修改和生成字符串的操作的实现方法都是另一个内存片段中新生成一个字符串对象。

创建字符串

str1 = "Left is short"
str2 = 'You need Python'

大小写转换

1. lower() and upper()

string1 = str1.lower()
string2 = str2.upper()

lower() 返回一个全小写形式的字符串。

upper() 返回一个全大写形式的字符串。

2. title() and capitalize()

string1 = str1.title()
string2 = str2.capitalize()

title() 返回所有单词首字母大写、其他字母小写的字符串。

capitalize() 返回句首字母大写、其他字母小写的字符串。

3. swapcase()

string = str1.swapcase()

swapcase() 返回对原字符串进行反转后的结果字符串。【大写->小写,小写->大写】

IS 判断

1. isalpha()isdecimal()isdigit()isnumeric() and isalnum()

str1.isalpha()
str1.isdecimal()
str2.isdigit()
str2.isnumeric()
str2.isalnum()

isalpha() 判断字符串是否只由字母组成。

以下中“数字digit”和“number数字”不是同一个概念。

isdacimal() 判断字符串是否只包含十进制数字字符。小数点等其他符号也会被判为False。

isdigit() 判断字符串是否只包含数字字符(包括十进制、Unicode 和全角字符)。如果有至少一个字符不是则返回False。

isnumeric() 判断字符串是否只包含数字字符(包括十进制、Unicode、全角字符和汉字)。

isalnum() 判断字符串是否只包含字母和阿拉伯数字字符。

2. isupper()islower() and istitle()

str1.isupper()
str2.islower()
str2.istitle()

isupper() 判断字符串是否全为大写。

islower() 判断字符串是否全为小写。

istitle() 判断字符串是否全为单词首字母大写、且非首字母全小写。

注意: title()istitle() 中单词的分隔符可以是任意非字母字符。平不是只有空格或句点。

3. isspace()isprintable() and isdentifier()

str1.isspace()
str2.isprintable()
str3.isdentifier()

isspace() 判断是否为空白字符,包含空格、制表符和换行符等。

isprintable() 判断是否为可打印字符。

isdentifier() 判断是否满足标识符定义规则。

填充

1. center(width[, fillchar])

str1.center()
posted @ 2023-09-12 22:08  Tatsukyou  阅读(6)  评论(0编辑  收藏  举报