Home > Net >  How to remove last character of a string
How to remove last character of a string

Time:03-25

I have many lines similar to

"HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|JJJ|          |"

"HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|HHH|" 

"HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|III|          |"

I want to remove last pipe and spaces from such lines which contains extra |

my required output is

"HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|JJJ|"

"HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|HHH|" 

"HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|III|"

I have tried for 1 string but the problem is this also eliminates the spaces present inside that string.

A=  "HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|JJJ|          |"
Y=A.split()
print(Y)

final=[]

if Y[-1]=='~':
    ab=Y[:-1]
    cd=''.join(ab)
    print(cd)
else:
    ef=''.join(Y)
    print(ef)

CodePudding user response:

use a regex with 1 or more spaces then a pipe then end of line.

your_string = re.sub("\s \|$","",your_string)

testing:

>>> your_string = "HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|JJJ|          |"
>>> re.sub("\s \|$","",your_string)
'HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|JJJ|'
>>> your_string = "HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|JJJ|"
>>> re.sub("\s \|$","",your_string)
'HHH |**** XYzz| *ABC*hgg|G~GG|G|HJJ|JJJ|'

CodePudding user response:

A = A[:-1] to remove the last character and A = A.strip() to remove leading and trailing spaces (not those within the text.

  • Related