[英]How to remove \n and \t from a list in python?
I have been trying to remove \\n and \\t from 2 lists in python but have been unable to do so. 我一直在尝试从python中的2个列表中删除\\ n和\\ t,但是一直无法删除。 Below is my code:
下面是我的代码:
A=[]
B=[]
C=[]
D=[]
.................
.................
df=pd.DataFrame(A,columns=['Rank'])
df['Company Name']=B
C=list(filter(lambda x: x != '\n', C))
C=list(filter(lambda x: x != '\t', C))
df['Type of organization']=C
D=list(filter(lambda x: x != '\n', D))
D=list(filter(lambda x: x != '\t', D))
df['Industry']=D
writer = pd.ExcelWriter('compdata.xlsx', engine='xlsxwriter')
df.to_excel(writer, index=False, sheet_name='report')
writer.save()
Kindly help me out as I have tried lambda as well but to no avail. 请帮我,因为我也尝试过lambda,但无济于事。 Every time I export the data frame to Excel, it gives me a lot of spaces in those 2 columns.
每次将数据框导出到Excel时,这两列都会给我很多空间。
Below is how C and D looks like: 下面是C和D的样子:
Rank Company Name \
0 1. Google (Alphabet)
1 2. ACUITY
2 3. The Boston Consulting Group
3 4. Wegmans Food Markets
Type of organization \
0 \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...
1 \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...
2 \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...
3 \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...
Industry
0 \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...
1 \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...
2 \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...
3 \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...
In actuality, Type of organization should have either "Public" or "Private". 实际上,组织的类型应为“公共”或“私人”。 It's just that the list has a lot of \\n and \\t before either of the aforementioned choices.
只是在上述任一选择之前,列表中都有很多\\ n和\\ t。
Try the following: 请尝试以下操作:
Using list comprehension : 使用列表理解 :
my_list = ['a', 'b', '\n', 'c', '\t', 'd']
my_list = [item for item in my_list if item not in ['\n', '\t']]
my_list = filter(lambda item: item not in ['\n', '\t'], my_list)
Edit: 编辑:
For the example of inputs added to the question, you can remove \\t
and \\n
like this: 对于添加到问题的输入示例,您可以这样删除
\\t
和\\n
:
c = [''.join(item.split()) for item in c]
Output: 输出:
>>> c = ['\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPublic', '\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPrivate', '\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPrivate', '\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPrivate']
>>>
>>> [''.join(item.split()) for item in c]
['??Pu??blic', '\\??tPri??vate', '\\??tPri??vate', '\\??tPri??vate']
Try this: 尝试这个:
C = [ x.replace('\t', '').replace('\n', '') for x in C ]
same for D
D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.