0

Hello I have a simple problem using Python but I don't achieve to solve it.

Here is my problem :

a = '2020-06-15'
a = a[::-2] + "01" # according to me with this a = '2020-06-01'

But when I printed a I get : '100101' for the value of a...

Could you help me please ?

Thank you !

Bob
  • 103
  • 1
  • 6
  • 1
    You should be using only one colon in your slice, right now the -2 is interpreted as the `step` (as in, it will iterate backwards through the list skipping 2 each time). `a[:-2]` instead will give you everything except for the last two characters – awarrier99 Jun 11 '20 at 18:33
  • 1
    You have an extra colon if you're trying to replace the last two characters of your string. Try `a = a[:-2] + "01"` –  Jun 11 '20 at 18:34

2 Answers2

1

It's almost correct, just remove a colon:

a = '2020-06-15'
a = a[:-2] + "01" # according to me with this a = '2020-06-01'
print(a)

Output:

2020-06-01
Red
  • 26,798
  • 7
  • 36
  • 58
1

The first time you use a colon is to slice a string, The number you provide after the second colon is the step size, I'll illustrate with an example:

a = '2020-06-15'
a[1:8] #Slices from index 1 to 8 
>>'020-06-'

But,

a[1:8:2] #Here it slices from index 1 to 8 with step size of 2(skipping one value between)
>>'000-'

Coming to your question, Use the first part to get your desired output:

a = a[:-2] + "01"
>>2020-06-01
Raghul Raj
  • 1,428
  • 9
  • 24