String determination operation:
= str " fahaf asdkfja \ T \ R & lt \ n-fjdhal 3453 " Print ( str.isspace () ) # If str contains only spaces Returns True Print (str.isalnum ()) # If str at least one character and all True character is a number or letter is returned Print (str.isalpha ()) # If str has at least one character and all characters are letters returns True Print (str.isdecimal ()) # If the string contains only digit returns True , full-width digital Print (str.isdigit ()) # If the string contains only digit returns True, full-width figures, (1), \ u00b2 ---> (Unicode) Print (str.isnumeric ()) # If the string contains only digital returns True, full-width numbers, characters digital Print (str.istitle ()) # If the string is the title of (each word is capitalized) True returns Print (str.islower ()) #All of these (case-sensitive) if the character string contains at least one of alphanumeric characters, and all lowercase, True is returned Print (str.isupper ()) # at least a case-sensitive character string if included, and all of these (case-sensitive) characters are uppercase, True is returned
Find the replacement string operations:
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所有元素合并为一个新的字符串