Python strip()和split()方法

1. Python strip()

语法描述:

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

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

返回值:

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

示例:

str1 = "0000000123456Awin_Ge3456700000000000"  #######去除首尾字符0#######
print str1.strip('0')            #######去除首尾字符0#######


str2 = "  Awin_Ge   "            
print str2.strip()   

输出结果如下:

123456Awin_Ge34567
Awin_Ge

从结果上看,可以注意到中间部分的字符并未删除。

以上下例演示了只要头尾包含有指定字符序列中的字符就删除

str3 = "1234Awin_Ge4321"
print str3.strip('123')

输出结果如下:

4Awin_Ge4

2. Python split()

语法描述:

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

返回值:

返回分割后的字符串列表

示例:

str4 = "This is string example!!!!!!!"
print str4.split()
print str4.split('i',1)
print str4.split('!')

输出结果如下:

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


猜你喜欢

转载自blog.csdn.net/ge341204/article/details/80715169