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
2
  • What isn't working? What output are you getting? Commented Jun 22, 2017 at 13:48
  • 2
    Simply do a.lstrip('@'). Commented Jun 22, 2017 at 13:50

3 Answers 3

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@@'
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

a.lstrip('@@@b') is misleading becauselstrip argument is a character set, not a string. Using lstrip may be convenient when the prefix is stored in a variable. stackoverflow.com/a/16891427/2325279 and stackoverflow.com/a/16891418/2325279 are both easy to read.
0
def remove(S): return S[4:] if S.startswith('@@@@') else S
>>> remove('@@@@b@@')
'b@@'
>>> remove('@@@b@@')
'@@@b@@'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.