十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
在Python中字符串是不可变变量,对其进行切片及其中的元素复制都会报错
成都创新互联公司服务项目包括罗庄网站建设、罗庄网站制作、罗庄网页制作以及罗庄网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,罗庄网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到罗庄省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!
>>> str = "This is Python" >>> str[0:3] = "abc" Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment
其常用的方法:
split
用法:str.split(sep=None, maxsplit=-1)
将字符串划分为序列
>>> env = "/usr/bin/python" >>> tmp_env = env.split("/") >>> tmp_env ['', 'usr', 'bin', 'python']
replace
用法:str.replace(old,new[,max])
将指定子串替换为另一个子串,并返回替换后的结果,但不会改变原String的内容
>>> str = "This are Python" >>> rep_str = str.replace("are","is") >>> rep_str 'This is Python' >>> str 'This are Python' >>> str = "This is Python,That is Great" >>> rep_str = str.replace("is","was",2) >>> rep_str 'Thwas was Python,That is Great'
find
用法:str.find(sub[, start[, end]])
在字符串中查找字串,若找到,则返回字串的第一个字符的索引,否则,返回-1
>>> str = "This is Python,Hello ,中国,您好" >>> fd_str = str.find("is") >>> fd_str 2 >>> str[fd_str] 'i' >>> fd_str2 = str.find("中") >>> str[fd_str2] '中' >>> str1 = "That is dog".find("G") >>> str1 -1
join
用法:str.join(iterable)
合并序列的元素
>>> dirs = ['','usr','bin','python'] >>> '/'.join(dirs) '/usr/bin/python' >>> num = [1,2,3,4] #合并数字列表,报错 >>> seq = '+' >>> seq.join(num) Traceback (most recent call last): File "", line 1, in TypeError: sequence item 0: expected str instance, int found >>> str1 = ["A","B","C"] #合并字符列表,OK >>> seq = "-" >>> seq.join(str1) 'A-B-C' >>> str1 = "ABCDE" >>> seq = "abcde" >>> seq.join(str1) 'AabcdeBabcdeCabcdeDabcdeE'
strip
用法:str.
strip
([chars])
将字符串开头和末尾的空白(不包括中间的空白)删除,并返回结果
>>> " Hello,World!".strip() 'Hello,World!' >>> "Hello,World ".strip() 'Hello,World' >>> " Hello,World ".strip() 'Hello,World' >>> "Hello, World! !".strip() 'Hello, World! !' >>> "www.baidu.com".strip("com") 'www.baidu.' >>> "www.baidu.com".strip(".com") 'www.baidu'
center
用法:str.
center
(width[, fillchar])
通过在两边填充字符(默认为空格)让string居中
>>> "0123456789".center(1) '0123456789' >>> "0123456789".center(-1) '0123456789' >>> "0123456789".center(10) '0123456789' >>> "0123456789".center(11) ' 0123456789' >>> "0123456789".center(11,"*") '*0123456789' >>> "0123456789".center(12,"*") '*0123456789*' >>> "0123456789".center(20,"*") '*****0123456789*****'
详细的String参数可参考官网文档:
https://docs.python.org/3.7/library/stdtypes.html?highlight=replace#str.replace