Home > Net >  Slicing the second last character
Slicing the second last character

Time:09-04

I have this string here '[2,3,1,1,]'

Im new to slicing and I only know how to slice from the start and from the end but not somewhere between, not even sure if that is possible.

could someone tell me how I can slice this '[2,3,1,1,]' to this '[2,3,1,1]' So removing the second last character only.

CodePudding user response:

If you just want to delete the second last character, your can do like this,

s = "[2,3,1,1,]"

s[:-2]   s[-1]
# '[2,3,1,1]'

s[:-2] -> Will slice the string from 0 to -2 index location (without -2 index)

s[-1] -> Will fetch the last element

s[:-2] s[-1] -> concatenation of the strigs

CodePudding user response:

If you're sure you have that string, slice both characters and add the ] back on!

source_string = "[2,3,1,1,]"
if source_string.endswith(",]"):
    source_string = source_string[:-2]   "]"

However, often lists stored as strings are not very useful - you may really want to convert the whole thing to a collection of numbers (perhaps manually removing the "[]" and splitting by ,, or using ast.literal_eval()), potentially converting it back to a string to display later

>>> source_string = "[2,3,1,1,]"
>>> import ast
>>> my_list = ast.literal_eval(source_string)
>>> my_list
[2, 3, 1, 1]
>>> str(my_list)
'[2, 3, 1, 1]'

CodePudding user response:

You can use this for this one case

txt = "[2,3,1,1,]"
print(f"{txt[:-2]}{txt[-1]}")

Even tho storing lists as string is a bit weird

txt[:-2] will get the characters from 0 index to -2 index

txt[-1] will get the last character which is "]"

then I concatenate both with an f"" string

You can use this if you don't wanna use an f string

print(txt[:-2], txt[-1], sep="")

the "sep" argument is so there won't be space between the two prints

  • Related