Home > Mobile >  Is there a way where i can remove trailing 1's at the end of a string as shown below
Is there a way where i can remove trailing 1's at the end of a string as shown below

Time:11-16

I have a list format as shown below.

stripped_list=['WLH1', 'GWJ1', 'AV11', 'UBN1']

I want to remove trailing 1's at the end but if i am using below code

stripped_list2 = [[item.replace('1', '') for item in z] for z in stripped_list]

it is stripping AV11 to AV only but i need AV1.

How to solve this?

I have a list format as shown below.

stripped_list=['WLH1', 'GWJ1', 'AV11', 'UBN1']

I want to remove trailing 1's at the end but if i am using below code

stripped_list2 = [[item.replace('1', '') for item in z] for z in stripped_list]

it is stripping AV11 to AV only but i need AV1.

How to solve this?

CodePudding user response:

Use re.sub with $ for match end of string for replace last 1:

import re

stripped_list=['WLH1', 'GWJ1', 'AV11', 'UBN1']

stripped_list2 = [re.sub( r'1$', '', z) for z in stripped_list]

print (stripped_list2)

['WLH', 'GWJ', 'AV1', 'UBN']

If need remove all last values:

stripped_list2 = [z[:-1] for z in stripped_list]

print (stripped_list2)

['WLH', 'GWJ', 'AV1', 'UBN']

CodePudding user response:

Using list comprehension, assuming 1 may or not may not be present as the last character and then removing it if its there -

stripped_list=['WLH1', 'GWJ1', 'AV11', 'UBN1']
print([item[:-1] if item[-1]=='1' else item for item in stripped_list])

Output:

['WLH', 'GWJ', 'AV1', 'UBN']

CodePudding user response:

Simple code - assuming 1 is always at the end:

stripped_list=['WLH1', 'GWJ1', 'AV11', 'UBN1']

for i, word in enumerate(stripped_list): 
    stripped_list[i] = word[:-1]
    
print(stripped_list)

CodePudding user response:

s = [i[:len(stripped_list)-1] for i in stripped_list]
  • Related