[英]python eval and string indexing
Let's say I have a string 假设我有一个字符串
string = '1234567890'
and I want a slice of that string defined by another string 我想要由另一个字符串定义的那个字符串的一部分
slice = '5:8'
This is easy to do with 这很容易做到
>>>string[5:8]
'678'
However the slice is passed in through a file and changes on user input. 但是,切片将通过文件传递,并根据用户输入进行更改。 Is their a way of doing something such as
是他们做某事的一种方式,例如
>>>string[eval(slice)]
'678'
When I do this I get 当我这样做时
5:8
^
SyntaxError: invalid syntax
I have a function that accounts for all four cases, I was just wondering if their was a more elegant way of doing this. 我有一个函数可以说明所有四种情况,我只是想知道它们是否是一种更优雅的方式。
Thanks for your answers. 感谢您的回答。
You are getting the syntax error since 5:8
isn't a valid Python statement on its own; 由于
5:8
本身并不是有效的Python语句,因此您会收到语法错误。 eval
expects normal Python code, not just fragments. eval
需要普通的Python代码,而不仅仅是片段。
If you really want to use eval
, you can say: 如果您真的想使用
eval
,可以说:
string = '1234567890'
sliceInput = '5:8'
result = eval('string[' + sliceInput + ']')
However this is not at all secure if you're allowing user input. 但是,如果您允许用户输入,则根本不安全。 A safer way would be:
一种更安全的方法是:
string = '1234567890'
sliceInput = '5:8'
sliceParts = sliceInput.split(':')
if len(sliceParts) != 2:
# Invalid input -- either no ':' or too many
else:
try:
start, end = [ int(x) for x in sliceParts ]
except ValueError:
# Invalid input, not a number
else:
result = string[start : end]
Note that slice()
is a built-in Python function, so it isn't considered good practice to use it as a variable name. 请注意,
slice()
是内置的Python函数,因此,将它用作变量名被认为不是好习惯。
How about: 怎么样:
string = '1234567890'
slice = '5:8'
sliceP = slice.split(':')
string[int(sliceP[0]):int(sliceP[1])]
The slice syntax isn't permitted outside of brackets, so it will break if you try to eval it on its own. slice语法不允许在方括号之外,因此如果您尝试自己对其进行评估,则它将断开。 If you really want to eval input from a file, you can construct the complete call as a string, then eval it:
如果您确实希望评估文件中的输入,则可以将完整的调用构造为字符串,然后评估它:
eval("string[" + slice + "]")
The usual caveats about eval
apply: a malicious user can get your program to execute arbitrary code this way, so you might be better off trying to parse out the bounds rather than eval
ing them. 有关
eval
的通常警告:适用于恶意用户的程序可以使您的程序以这种方式执行任意代码,因此尝试解析边界而不是eval
边界可能会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.