一、split()函數可以將一個字符串分裂成多個字符串組成的列表。
語法格式:
str.split(sep, maxsplit)sep 是分割符,不寫分割符時表示所有的空字符,包括空格、換行(\n)、制表符(\t)等,有分隔符時,以該分隔符進行分割。
maxsplit是分割次數,默認為 -1, 即分隔所有。
返回:分割後的字符串列表。
二、 strip() 方法用於移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。
注意:該方法只能刪除開頭或是結尾的字符,不能刪除中間部分的字符。
strip()方法語法:
str.strip();參數為空:默認刪除空白符(包括'\n', '\r', '\t', ' ')
返回:移除字符串頭尾指定的字符生成的新字符串。
示例兩種方式返回刪除換行符的列表:
1、使用read()、split,返回無換行符的字符串列表txt_list[]
file=open(r'D:\\MyCode\\shiyefuwu\\test.txt')txt=file.read()txt_list=txt.split('\n')print(txt_list)file.close()2、使用readlines()、strip()、append等,返回無換行符的字符串列表txt_list[]
file=open(r'D:\\MyCode\\shiyefuwu\\test.txt')txt_list=[]forlineinfile.readlines():line=line.strip()txt_list.append(line)print(txt_list)file.close()strip() :去除字符串兩邊的空格,此次的空格包含'\n', '\r', '\t', ' '
3、綜合示例
ip_address = []withopen(r'D:\\MyCode\\shiyefuwu\\test.txt', 'r') asf1:foripinf1.readlines():ifip!= None:# 從文件中讀取行數據時,會帶換行符,使用strip函數去掉 換行符後存入列表ip_address.append(ip.strip("\n"))f1.close()print(ip_address[1]) #顯示列表第2個值