python常用处理字符串函数的详细分析
作者:互联网
1.split
将一个字符串拆分成一个子字符串列表,列表中的子字符串正好可以构成原字符串。
两个参数:
第一个参数表示使用哪个字符进行拆分。
第二个参数表示进行拆分的次数(两次拆分,可得3 个子字符串)
#1、无参数
string1 = "My deliverable is due in May"
string1_list1 = string1.split()
#2、单参数
string2 = "Your,deliverable,is,due,in,June"
string2_list = string2.split(',')
#3、双参数 使用空格分割,分割两次,而且是前面两次的空格,后变为三个字符串
string1 = "My deliverable is due in May"
string1_list2 = string1.split(" ",2)
2.join
用 join 函数将列表中的子字符串组合成一个字符串
print("Output #25: {0}".format(','.join(['Your', 'deliverable', 'is', 'due', 'in', 'June'])))
#out:
#Your,deliverable,is,due,in,june
3.strip/lstip/rstrip
从字符串两端删除不想要的字符
#使用参数设定从字符串两端删除的字符(或字符串)
#lstrip、rstrip 和 strip 函数分别从字符串的左侧、右侧和两侧
#删除空格、制表符和换行符以及其他字符
#1.如果是删除空格,换行符以及制表符,直接调用即可
string3 = " Remove unwanted characters from this string.\t\t \n"
print("Output #26: string3: {0:s}".format(string3))
string3_lstrip = string3.lstrip()
print("Output #27: lstrip: {0:s}".format(string3_lstrip))
string3_rstrip = string3.rstrip()
print("Output #28: rstrip: {0:s}".format(string3_rstrip))
string3_strip = string3.strip()
print("Output #29: strip: {0:s}".format(string3_strip))
#2.其他字符需要往括号内加入
string4 = "$$Here's another string that has unwanted characters.__---++"
print("Output #30: {0:s}".format(string4))
string4 = "$$The unwanted characters have been removed.__---++"
string4_strip = string4.strip('$_-+')
print("Output #31: {0:s}".format(string4_strip))
4.replace
string5 = "Let's replace the spaces in this sentence with other characters."
string5_replace = string5.replace(" ", ",")
print("Output #33 (with commas): {0:s}".format(string5_replace))
5.lower/upper/capitalize
lower 将字符串中的字母转换为小写
upper 将字符串中的字母转换为大写
capitalize 对字符串中的第一个字母upper,对其余的字母 lower
string6 = "Here's WHAT Happens WHEN You Use lower."
print("Output #34: {0:s}".format(string6.lower()))
string7 = "Here's what Happens when You Use UPPER."
print("Output #35: {0:s}".format(string7.upper()))
string5 = "here's WHAT Happens WHEN you use Capitalize."
print("Output #36: {0:s}".format(string5.capitalize()))
string5_list = string5.split()
print("Output #37 (on each word):")
for word in string5_list:
print("{0:s}".format(word.capitalize()))
标签:format,python,print,strip,字符串,Output,详细分析,string3 来源: https://www.cnblogs.com/hiccuplh/p/16574490.html