ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python常用处理字符串函数的详细分析

2022-08-11 01:32:29  阅读:143  来源: 互联网

标签:format python print strip 字符串 Output 详细分析 string3


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有