Home > database >  delete characters in a string from begining to ']' character
delete characters in a string from begining to ']' character

Time:10-02

Delete characters upto and including ']'

a="[12] hi how are you [1]" 
b="[13][14] hello" 

expected output :

a="hi how are you [1]"

b=" hello"  

CodePudding user response:

You can use regular expression to achieve this

import re

txt = "[12] hi how are you" 
x = re.sub("\[[0-9] \]\s*", "", txt)
print(x)

CodePudding user response:

You can make use of rindex():

def doIt(a):
    if "]" in a:
        x = a.rindex("]")
        a = a[x   1 :].strip()
    return a

Lets Test it:

a = "[12] hi how are you"
b = "[13][14] hello"
c = "kahbscdkashju asjhd bkaisd b dab bui"
print(doIt(a))
print(doIt(b))
print(doIt(c))

Output:

hi how are you
hello
kahbscdkashju asjhd bkaisd b dab bui

You can also write custom method without using any built-in string method.

def doIt(a):
    ans = []
    for i in range(len(a) - 1, -1, -1):
        if a[i] == "]":
            break
        ans.insert(0, a[i])
    return "".join(ans).strip()
  • Related