python 多层list到str的转换 和 str中换行符\n的保存

1.多层list到str的转换
正常简单的list到str的转化如下:

d = ['a', 'b ', 'c']
q = " ".join(str(i) for i in d )
print('this is q:',q)

print:
this is q: a b  c

这个对于简单的list很实用。但是遇到了一个问题多层list,比如list = [[a,b,c],[d,f,g]].这样的list的格式的数据类型就不太好处理了。

d = [['a', 'b', 'c'],['e', 'f', 'g']]
list_new = []
for i in range(len(d)):
    list_new.extend(d[i])
print('this is list_new:',list_new)
q = " ".join(str(i) for i in list_new )
print('this is q:',q)


print:
this is list_new: ['a', 'b', 'c', 'e', 'f', 'g']
this is q: a b c e f g

2.list2str中的’\n’问题
在list转换为str的过程中存在一个“\n”换行符号的问题,就是说,list的情况下“\n”不会换行,但是转变成str后会自己换行。例如:

b = ['a', 'b\n ', 'c']
q = " ".join(str(i) for i in b )
print('this is q:',q)

print:
this is q: a b
  c

所以会出现一个换行,并且原本的list[1] = ‘b\n’ 变成了‘b’,为了保留原始数据,我们对“ ”.join()函数进行修改,添加if 语句,将’\n’,替换为str中的转义符‘\n’.

b = ['a', 'b\n ', 'c']
b2Str = ' '
for i in b:
    if '\n' in str(i):
        node_new = str(i).replace('\n', '\\n')
        b2Str = b2Str + ' ' + node_new
        continue
    b2Str = b2Str + ' ' + str(i)
print('this is train_node1: ', b2Str)

print:
this is train_node1:    a b\n  c

3.删除包含’\n’的数据

s=['Ye kr kia rhy hain pehly ghazian ko mar dia ab Dr. Fara.\n']
s=[x.strip() for x in s if x.strip()!='']
print(s)

print
['Ye kr kia rhy hain pehly ghazian ko mar dia ab Dr. Fara.']

感觉很多最基础的内容网上的一些教程很讲到,比如说最简单的list2str,但是出现一些特殊的情况,别人也没遇到的话,就要自己去理解去解决,比如说 str(i).replace(’\n’, ‘\n’)中str(i)在replace后是不会变的,如何保留‘\n’,而不让它换行等,很多都需要自己去看,路很长。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值