关于python的字符串操作
2020-12-13 15:51
标签:汉字 oem unicode info tle rip poe for enter 字符串的查找的替换操作: 大小写转换: 去除空白: 关于python的字符串操作 标签:汉字 oem unicode info tle rip poe for enter 原文地址:https://www.cnblogs.com/icebluelp/p/11616434.htmlstr = "fahaf asdkfja\t \r \n fjdhal 3453"
print(str.isspace()) # 如果str中只包含空格,则返回True
print(str.isalnum()) # 如果str至少有一个字符并且所有字符都是数字或者字母则返回True
print(str.isalpha()) # 如果str至少有一个字符并且所有字符都是字母则返回True
print(str.isdecimal()) # 如果string只包含数字则返回True, 全角数字
print(str.isdigit()) # 如果string只包含数字则返回True,全角数字、(1)、\u00b2--->(unicode)
print(str.isnumeric()) # 如果string只包含数字则返回True,全角数字,汉字数字
print(str.istitle()) # 如果string是标题化的(每个单词的首字母大写)则返回True
print(str.islower()) # 如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True
print(str.isupper()) # 如果string中包含至少一个区分大小写的字符,并且所有这些(區分大小写的)字符都是大写,则返回True
str = "hello hello"
print(str.startswith("hello")) # 检查字符串是否是以hello开头,是则返回True
print(str.endswith("hello")) # 检查字符串是否是以hello结束,是则返回True
print(str.find("lo")) # 检测lo是否包含在str中,如果start和end指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回 -1
print(str.rfind("lo")) #类似于find()方法,不过是从右边开始查找
print(str.index("lo")) #跟find()方法类似,只不过如果lo不在str会报错
print(str.rindex("lo")) # 类似于index()方法,不过是从右边开始查找
print(str.replace("hello", "HELLO", 1)) # 将hello替换为HELLO,替换次数为1次
# 大小写转换
str = "hello pyTHon"
print(str.capitalize()) # 把字符串的第一个字母大写
print(str.title()) # 首字母大写
print(str.lower()) # 将所有大写转换为小写
print(str.upper()) # 将所有小写转换为大写
print(str.swapcase()) # 将大小写翻转
# 文本对齐
poem = ["静夜思",
"李白",
"床前明月光",
"疑似地上霜",
"举头望明月",
"低头思故乡"]
for i in poem: # 左对齐,返回一个填充10个单位的全角空格字符串
print("|%s|" % i.ljust(10), " ")
print()
for i in poem: # 右对齐,返回一个填充10个单位的全角空格字符串
print("|%s|" % i.rjust(10), " ")
print()
for i in poem: # 居中,返回一个填充10个单位的全角空格字符串
print("|%s|" % i.center(10, " "))
# 去除空白
poem = ["静夜思",
"李白",
"\t\n床前明月光",
"疑似地上霜\t",
"\t举头望明月\t\n",
"低头思故乡"]
for i in poem: # 去除左侧空白字符
print("|%s|" % i.lstrip())
print("*" * 10)
for i in poem: # 去除右侧空白字符
print("|%s|" % i.rstrip())
print("*" * 10)
for i in poem: # 去除两侧空白字符
print("|%s|" % i.strip())
# 拆分和连接
str = "how are you"
print(str.partition(" ")) # 把字符串分成一个3元素的元组
print(str.rpartition(" ")) # 类似partition()方法,不过是从右边开始
print(str.split()) # 以空白字符(\r \t \n 空格)为分隔符拆分字符串
print(str.splitlines()) # 以 行(\r \n \r\n)为分隔符拆分字符串
print(" ".join(str)) # 以" "(空格)作为分隔符,将strongoing所有元素合并为一个新的字符串