简体   繁体   中英

How to convert this string into a list in python

I have the following code:

import re
codes = re.compile(r"\((\d+)\)")
for code in Fixed:
    co_codes = ' '.join(codes.findall(code))
    print(co_codes)

which gives me the following string:

04344
044
04344

I am trying to have all the elements in one list like this:

co_codes = [04344, 044, 04344] 

how can I do that.

Note there are almost 10000 numbers not only three

notebook code

You are probably looking for the splitlines method.

>>> s = '''04344
... 044
... 04344'''
>>> s.splitlines()
['04344', '044', '04344']

This sounds like a simple .split() would work:

a = """04344
044
04344"""
a.split()

You can just generate a list in one shot with list comprehension like this:

import re

codes = re.compile(r"\((\d+)\)")
co_codes = [ ''.join(codes.findall(code)) for code in Fixed ]

It will give you a list with all strings output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM