简体   繁体   English

如何将带有分隔符的字符串转换为Python中的字符串列表?

[英]How to convert string with a delimiter to list of strings in Python?

I'm querying a database and get this text: 我正在查询数据库并获得以下文本:

"('username', '192.168.1.1', datetime.datetime(2013, 1, 3, 7, 18))"

I want to split into list like this: 我想分成这样的列表:

['username', '192.168.1.1', datatime.datetime(2013, 1, 3, 7, 18)]

So, which way is the best way? 那么,哪种方法是最好的方法? I'm using Python 2.4. 我正在使用Python 2.4。

One way would be to use eval and list : 一种方法是使用evallist

>>> import datetime
>>> string = "('username', '192.168.1.1', datetime.datetime(2013, 1, 3, 7, 18))"
>>> list(eval(string))
['username', '192.168.1.1', datetime.datetime(2013, 1, 3, 7, 18)]

eval evaluates the string as a Python expression, here producing a tuple containing the two strings and a datetime instance. eval将字符串评估为Python表达式,在此生成一个包含两个字符串和一个datetime实例的元组。 list converts this tuple to a list. list将此元组转换为列表。


Caution: eval will potentially execute any valid Python code, even malicious code. 注意: eval可能会执行任何有效的Python代码,甚至是恶意代码。 There are safer alternatives such as ast.literal_eval which could be used if you're not sure whether you trust what's in your database. 如果不确定您是否信任数据库中的ast.literal_eval ,可以使用更安全的替代方法,例如ast.literal_eval

You can use maxsplit parameter of the split function: 您可以使用split函数的maxsplit参数:

your_string = "('username', '192.168.1.1', datetime.datetime(2013, 1, 3, 7, 18))"
your_string[1:-1].split(",", 2)

# Returns:
# ["'username'", " '192.168.1.1'", ' datetime.datetime(2013, 1, 3, 7, 18)']

As noted in jonrsharpe comment, it looks like you are falling in a trap you have just digged yourself. 正如jonrsharpe评论中所指出的jonrsharpe ,您似乎正陷入自己刚刚jonrsharpe的陷阱中。

Any correct database can give you the individual columns, and if you correctly do the query, you get them in proper format. 任何正确的数据库都可以为您提供各个列,如果正确执行查询,则会以正确的格式获取它们。

Assuming you can use a DB-API 2.0 described in PEP 249 , and assuming conn is an open connection to your database, you should do something like : 假设您可以使用PEP 249中描述的DB-API 2.0,并假定conn是到数据库的开放连接,则应执行以下操作:

curs = conn.cursor()
curs.execute('SELECT name, ip, dat FROM tab')
t = curs.fetchone()

and t should directly be the tuple ('username', '192.168.1.1', datatime.datetime(2013, 1, 3, 7, 18)) (use list(t) if you need a list ...) t应该直接是元组('username', '192.168.1.1', datatime.datetime(2013, 1, 3, 7, 18)) (如果需要列表,请使用list(t) ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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