设为首页 加入收藏

TOP

Python之字符串实例
2019-07-25 14:17:31 】 浏览:65
Tags:Python 字符串 实例

>>> str = "This is Python"
>>> str[0:3] = "abc"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment


Python之字符串实例


其常用的方法:


用法:str.split(sep=None, maxsplit=-1)


将字符串划分为序列


>>> env = "/usr/bin/python"
>>> tmp_env = env.split("/")
>>> tmp_env
['', 'usr', 'bin', 'python']


Python之字符串实例


用法: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'


Python之字符串实例


用法: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


Python之字符串实例


用法: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 "<stdin>", line 1, in <module>
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'


Python之字符串实例


用法:str.strip([chars])


将字符串开头和末尾的空白(不包括中间的空白)删除,并返回结果


Python之字符串实例


用法: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*****'


Python之字符串实例


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python函数参数及使用 下一篇10道Python常见面试题

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目