Python之字符串实例

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之字符串实例

其常用的方法:

split

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

将字符串划分为序列

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

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'

Python之字符串实例

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

Python之字符串实例

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 "<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之字符串实例

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.linuxidc.com".strip("com")
'www.linuxidc.'
>>> "www.linuxidc.com".strip(".com")
'www.linuxid'

Python之字符串实例

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*****'

Python之字符串实例

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/692d5e206561dbf45d75d6120fca3c37.html