暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Python字符串操作-生成无换行符的列表

云自由 2020-12-02
397

一、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=[]
for line in file.readlines():
line=line.strip()
txt_list.append(line)
print(txt_list)
file.close()

strip()  :去除字符串两边的空格,此次的空格包含'\n', '\r',  '\t',  ' '

3、综合示例

ip_address = []
with open(r'D:\\MyCode\\shiyefuwu\\test.txt', 'r') as f1:
   for ip in f1.readlines():
       if ip != None:
           # 从文件中读取行数据时,会带换行符,使用strip函数去掉 换行符后存入列表
           ip_address.append(ip.strip("\n"))
f1.close()

print(ip_address[1])  #显示列表第2个值



文章转载自云自由,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论