A convenient function rstrip that removes strings from the right. I used it as follows.
x = 'abcdefg'
x.rstrip('efg')
print(x)
Then the output is
abcd
Will be returned.
This time, I was writing a program that deletes the "_1" after the one with "_1" from the elements of the list, but in places other than "_1" such as "101_1" and "141_1", "1" I noticed that there was an error in the part containing'. After all, when I wondered and investigated, it seems that rstrip does not delete only the argument ('1'), but also deletes only'' or '1'. In other words, the above example is as follows.
x = 'abcdefggefgfegef'
x.rstrip('efg')
print(x)
Then the output does not change
abcd
For example, in the program I wrote this time, I can modify it as follows.
before
list = ['101_1', '102_1', '102_2', '103_1']
list = [x.rstrip('_1') for x in list]
after
list = ['101_1', '102_1', '102_2', '103_1']
list = [x.replace('_1','') for x in list]
Of course this is not exact. I did this under the assumption that _1 is attached only at the end, but if you are curious, use a regular expression.
Recommended Posts