Reputation: 216
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.
Upvotes: 1
Views: 4556
Reputation: 5005
Using built-in functions such as str.rstrip
l = '[2,3,1,1,]'
l_new = f"{l.rstrip('],')}]" # it doesn't matter the order!
print(l_new)
or str.rpartition
a, _, b = l.rpartition(',')
l_new = a + b
print(l_new)
you can avoid an explicit slicing. See doc for details.
The 1st approach is universal, hence doesn't produce any side-effects. The 2nd may give rise to side-effects if the final last character is not a ,
. If necessary use a check, i.e. str.endswith
, to fix it.
Upvotes: 0
Reputation: 684
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
Upvotes: 0
Reputation: 16081
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
Upvotes: 4
Reputation: 18930
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]'
Upvotes: 1