python 字符串 换行保存在列表里 python中如何将文本中的字符串单独提取出来,去空格去换行...

python\u53bb\u9664\u5b57\u7b26\u4e32\u5217\u8868\u4e2d\u7684\u6362\u884c\u7b26

>>>
string
=
'''a_b_c_001
a_b_c_002
a_b_c_003'''
>>>
string.splitlines()
['a_b_c_001',
'a_b_c_002',
'a_b_c_003']
>>>
#
\u5b57\u7b26\u4e32\u64cd\u4f5c\uff0csplitlines\u51fd\u6570\u5c06\u5b57\u7b26\u4e32\u6309\u884c\u5206\u5272\u5e76\u8fd4\u56de\u4e00\u4e2a\u5217\u8868

list_tmp=[]f = open('file_name.txt','r')for i in f.readlines(): list_tmp.append(i.strip())f.close()print list_tmp \u8fd8\u6709\u6362\u884c\u7b26\uff1f

可以使用‘\n’来分割这个字符串获得一个列表。
比如你的这个字符串输入存在变量test_string中,那么test_string.split('\n')就是一个列表,其中有3个元素,每个元素是一行字符串(没有换行符 )

>>> string = '''a_b_c_001
a_b_c_002
a_b_c_003'''
>>> string.splitlines()
['a_b_c_001', 'a_b_c_002', 'a_b_c_003']
>>>
# 字符串操作,splitlines函数将字符串按行分割并返回一个列表

s = '''a_b_c_001
a_b_c_002
a_b_c_003
'''
lstr = list(s)

用split分隔。或者正则。。。

a="""
a_b_c_001
a_b_c_002
a_b_c_003
"""
import re
p=re.compile("([^_\n]+)_([^_]+)_([^_]+)_([^_]+)\n")
result=p.findall(a);
print result
结果是
[('a', 'b', 'c', '001'), ('a', 'b', 'c', '002'), ('a', 'b', 'c', '003')]

扩展阅读:python换行三种方法 ... python换行符 n怎么用 ... python怎么换行写代码 ... python中写入文件如何换行 ... python编程时怎么换行 ... python 字符串 替换 ... python换行符是什么 ... python换行输出重复字符串 ... python代码大全 ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网