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; eval
expects normal Python code, not just fragments.
If you really want to use eval
, you can say:
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.
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. 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.
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.