简体   繁体   中英

Can I save a range to a variable?

Is there any way to assign an interval in a variable?

For example

my_string = "abcdef"
my_interval = 1:3
print(my_string[my_interval])

I wish to return bc . However, the second line does not work.

You need to use the python builtin function slice() to assign the slice to a variable. Your current syntax is not a valid python syntax.

>>> my_string = "abcdef"
>>> my_interval = slice(1, 3)
>>> print(my_string[my_interval])

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