Python Forum
increase and decrease a slice value? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: increase and decrease a slice value? (/thread-30869.html)



increase and decrease a slice value? - KEYS - Nov-10-2020

say i have a list
[1,2,3,4,5,6,7]

and id like to print, 3,4,5 then 2,3,4,5,6 finally 1,2,3,4,5,6,7
using a for loop, and a slice value within its body is it possible to add to a set slice value?

as this doesn't work i will present it as pseudo code as an example to possibly better illustrate.

inv=[1,2,3,4,5,6,7]

for i in range(0,3,1):
add=(inv[3-1:4+1])

print (add)

The [3-1:4+1] being the pseudo part of the code for now as it doesn't increment on each pass. It only changes the value of the slice the one time.


RE: increase and decrease a slice value? - deanhystad - Nov-10-2020

You should just try these things and see if they work.
Output:
>>> x='123456789' >>> y=x[3-1:3+1] >>> y '34' >>> for a in range(3): print(f'x[3-{a}:3+{a}] = "{x[3-a:3+a]}"') x[3-0:3+0] = "" x[3-1:3+1] = "34" x[3-2:3+2] = "2345" >>>
I do a lot of testing using the Python console built into IDLE or running python in a shell window. For just trying things like this it is much quicker than writing a program. You also have the advantage of built in interactive help.
Output:
>>> type(x) <class 'str'> >>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> help(str.replace) Help on method_descriptor: replace(self, old, new, count=-1, /) Return a copy with all occurrences of substring old replaced by new. count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences. If the optional argument count is given, only the first count occurrences are replaced. >>>



RE: increase and decrease a slice value? - KEYS - Nov-10-2020

You nailed it XD
thank you