Python学习笔记(一)字符串内建函数

发布于 2021-04-08  638 次阅读


Count

可以统计字符出现的次数,示例:

sen = "please enjoy the pain which is unable to avoid."
print("Count 可以统计字符出现的次数")
print("示例:\n统计P共出现了" + str(sen.count("p")) + "次") 

Replace

可以进行替换字符串,示例:

sen = "please enjoy the pain which is unable to avoid."
print("Replace 可以进行替换字符串")
print("示例:\n把pain替换成happy => " + str(sen.replace('pain','happy')))

Splite

可以指定分隔符,把一个字符串分割为多个字符串,示例:

sen = "please enjoy the pain which is unable to avoid."
print("Splite 可以指定分隔符,把一个字符串分割为多个字符串。")
print("示例:\n以空格为分隔符分割字符串 => " + str(sen.split(" ")))

Capitalize

可以将字符串的第一个英文字母转换为大写,示例:

sen = "please enjoy the pain which is unable to avoid."
print("Capitalize 可以将字符串的第一个英文转换为大写。")
print("示例:\n转换前:"+ sen + "\n转换后:" + str(sen.capitalize()))

Lower

可以将字符串中的所有英文字母转换为小写,示例:

sen = "please enjoy the pain which is unable to avoid."
ter = "PHP"
print("Lower 可以将字符串中的所有英文转换为小写。")
print("示例:\n转换前:" + ter + "\n转换后:" + str(ter.lower()))

Swapcase

可以将字符串中英文字母的大小写互换,示例:

sen = "please enjoy the pain which is unable to avoid."
ter = "PHP"
ps = "I have a very lovely cat."
print("Swapcase 可以将字符串中英文字母的大小写互换。")
print("示例:\n转换前:" + ps + "\n转换后:" + str(ps.swapcase()))

Title

可以将每个单词的首字母转换为大写,示例:

sen = "please enjoy the pain which is unable to avoid."
ter = "PHP"
ps = "I have a very lovely cat."
print("Title 可以将每个单词的首字母转换为大写。")
print("示例:\n转换前:" + sen + "\n转换后:" + str(sen.title()))

Upper

可以将变量字符转换为大写字符串,示例:

sen = "please enjoy the pain which is unable to avoid."
ter = "PHP"
ps = "I have a very lovely cat."
print("Upper 可以将变量字符转换为大写字符串")
print("示例:\n转换前:" + sen + "\n转换后:" + str(sen.upper()))

Startswith

可以判断字符串指定范围内是否以指定字符开始,示例:

sen = "please enjoy the pain which is unable to avoid."
ter = "PHP"
ps = "I have a very lovely cat."
print("Startswith 可以判断字符串指定范围内是否以指定字符开始。")
print("示例:")
test1 = str(sen.startswith("p"))
if(test1 == "True"):
    print("如果sen变量句子开头是以p开头你才能看到这条消息~")
else:
    print("字符串开头不是P!")
print("\n")

test2 = str(sen.startswith("i"))
if(test2 == "True"):
    print("如果sen变量句子开头是以i开头你才能看到这条消息~")
else:
    print("字符串开头不是i!")
print("\n")

test3 = str(sen.startswith("e",7))
if(test3 == "True"):
    print("如果sen变量句子第8个字符是以e开头你才能看到这条消息~")
else:
    print("第八个字符不是e!")
print("\n")

test4 = str(sen.startswith("o",7))
if(test4 == "True"):
    print("如果sen变量句子第8个字符是以o开头你才能看到这条消息~")
else:
    print("第八个字符不是o!")

Endswith 方法和 Startswith 用法区别不大就不再演示了,详见菜鸟教程:Endswith 方法 | Startswith 用法

字符串对齐函数

Center方法可以把原字符串居中,并使用空格填充成指定长度的新字符串,默认的填充字符为空格,示例:

sen = "please enjoy the pain which is unable to avoid."
ter = "PHP"
ps = "I have a very lovely cat."
print("字符串对齐函数")
print("Center 方法可以把原字符串居中,并使用空格填充成指定长度的新字符串,默认的填充字符为空格。")
print("示例:\n" + ter.center(50,"="))
print("\n")

print("ljust/rjust 方法效果同上,区别是左对齐和右对齐。")
print("示例:\n" + ter.ljust(50,"*"))
print("示例:\n" + ter.rjust(50,"&"))

只是当时已惘然。