0

I am trying to remove all the prefix "@" from the string "@@@@b@@" Expected output is "b@@" (not all the '@' but only prefix) If there is no prefix "@", it should return the original string itself This is the code, I am trying : (I am using python 2.X)

mylist = []




def remove(S):
    mylist.append(S)
    j=0
    for i in range(len(S)):
        if mylist[0][j]=='@':
            S = S[:j] + S[j + 1:]
            j+=1
            return S


        else:
            return S
            break




a = remove("@@@@b@@")

print a
pycode
  • 5
  • 3

3 Answers3

7

Use lstrip()

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed.

>>> "@@@@b@@".lstrip("@")
'b@@'
Christian König
  • 3,437
  • 16
  • 28
1

Python 3.9
There are two new string methods, removesuffix() and removeprefix()

"HelloWorld".removesuffix("World")

Output: "Hello"

"HelloWorld".removeprefix("Hello")

Output: "World"

Before Python 3.9

  1. Using lstrip() (See Christians answer)
    Be careful using lstrip and rstrip. If you are trying just to remove the first few letters. lstrip() and rstrip() will keep removing letters until it reaches an unrecognizable one.

      a = "@@@b@@"  
      print(a.lstrip('@@@b'))
    

Output:
Above output is a empty string, lstrip strips off everything!

a = "@@@b@@c"
print(a.lstrip('@@@b'))

Output: c

  1. Use a regular expression
  import re
  url = 'abcdc.com'
  url = re.sub('\.com$', '', url)
John Salzman
  • 500
  • 5
  • 14
  • 1
    `a.lstrip('@@@b')` is misleading because`lstrip` argument is a character set, not a string. Using lstrip may be convenient when the prefix is stored in a variable. https://stackoverflow.com/a/16891427/2325279 and https://stackoverflow.com/a/16891418/2325279 are both easy to read. – Petr Vepřek Dec 01 '20 at 14:56
0
def remove(S): return S[4:] if S.startswith('@@@@') else S
>>> remove('@@@@b@@')
'b@@'
>>> remove('@@@b@@')
'@@@b@@'