Python strip()、split()和rstrip()方法

1. Python strip()

语法描述:

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

返回值:
返回值是返回移除字符串头尾指定的字符生成的新字符串

示例:

a1="00000123hello_world12300000000"
print a1.strip("0")  #去除首尾字符0

a2="     hello_world    "
print a2.strip()  #去除首尾空字符

输出结果:

123hello_world123
hello_world

2. Python split()

语法描述:

通过指定分隔符对字符串进行分割并返回一个列表,默认分隔符为所有空字符,包括空格、换行(\n)、制表符(\t)等

返回值:
返回分割后的字符串列表

示例:

a3="This is a example!!!!!!!!!"
print a3.split()  #将字符串按空格分割
print a3.split('i',1)  #将字符串按第一个i分割且i被分隔符替换
print a3.split('!')  #将字符串按!分割且!被分隔符替换

输出结果:

['This',  'is',  'a ', 'example!!!!!!!!!']
['Th', 's is a example!!!!!!!!!']
['This is a example', '','','','','','','','']

3. Python rstrip()

语法描述:

Python rstrip() 删除 string 字符串末尾的指定字符(默认为空格)。

返回值:
返回删除 string 字符串末尾的指定字符后生成的新字符串。

示例:

a4="        This is string example!       "
print a4.rstrip()    #删除字符串尾部空格
a5="88888888This is string example!8888888"
print a5.rstrip('8')    #删除字符串尾部8

输出结果:

        This is string example!
88888888This is string example!

你可能感兴趣的:(Python strip()、split()和rstrip()方法)