パイソンの文字列操作

文字列の決意操作:
= STR " fahaf asdkfja \ T \ R&LT \ n型fjdhal 3453 " 
を印刷(str.isspace() )   strは唯一のスペースが含まれている場合、Trueを返します 
印刷(str.isalnum())  strの場合は、少なくとも一つの文字とすべてを真の文字は数字または文字が返されている 
印刷(str.isalpha())  strが、少なくとも一つの文字を持っており、すべての文字が英字であればTrueを返す 
印刷(str.isdecimal())  文字列だけの数字がTrueを返すが含まれている場合、全幅デジタル 
印刷(str.isdigit())    文字列は、唯一の桁が真、フル幅の数値、(1)、\ u00b2 --->(ユニコード)を返すが含まれている場合 
の印刷(str.isnumeric())    文字列にのみ含まれている場合デジタルTrueを返し、全角数字、文字のデジタル 
印刷(str.istitle())  文字列は、(各単語が大文字である)がtrueを返すとのタイトルであれば 
印刷(str.islower())  これらのすべて(大文字と小文字を区別)文字列は、少なくとも英数字の一つであり、すべての小文字が含まれている場合、真が返される 
印刷(str.isupper())    含まれている場合、少なくとも、大文字と小文字を区別した文字列を、これらの(大文字と小文字を区別)のすべての文字は大文字、真が返されます

 

置換文字列操作を探します:

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所有元素合并为一个新的字符串

 

 

おすすめ

転載: www.cnblogs.com/icebluelp/p/11616434.html