user1886376
user1886376

Reputation:

How to remove the first few characters of a string?

I have here this string '+ + + + + R1 VSS VDD GND 3123123' and need to remove all first '+' characters from it. I wrote this code here,

def clear_string(s):
    c = "+"
    for j in range(0, len(c)):
        s = s.replace(c[j], "")
    return s

but it removes all the '+' characters from the string, but I need to delete only the first '+' symbols, how to do it ?

Upvotes: 0

Views: 262

Answers (4)

mgilson
mgilson

Reputation: 309939

For completeness, a simple regex will work too (although the already proposed lstrip is better for simple replacements):

>>> import re
>>> re.sub(r'^(\+\s*)+', '', '+ + + + + R1 VSS VDD GND 3123123')
'R1 VSS VDD GND 3123123'
>>> re.sub(r'^(\+\s*)+', '', '+ + + + + R1 VSS VDD GND 3123123 ++++')
'R1 VSS VDD GND 3123123 ++++'

Upvotes: 0

roippi
roippi

Reputation: 25954

s = '+ + + + + R1 VSS VDD GND 3123123'

s.lstrip(' +')
Out[13]: 'R1 VSS VDD GND 3123123'

If you need to keep the leading spaces intact:

s.replace('+','',5) #limit the times you do the replace operation, only works if you know how many to do
Out[14]: '     R1 VSS VDD GND 3123123'

Upvotes: 1

otaku
otaku

Reputation: 1029

You could run a loop starting from the beginning and count upto the index where the + signs end in this case when you get str[i]=='R' so now that you have your index from where your string starts just get that part using a slice like str[5:]

Upvotes: -1

mdml
mdml

Reputation: 22882

You can use lstrip() to remove any leading characters in your string that match a given set of characters. In this case, you want to remove '+' and spaces.

Demo

>>> s = "+ + + + + R1 VSS VDD GND 312312"
>>> s.lstrip("+ ")
'R1 VSS VDD GND 312312'

Upvotes: 5

Related Questions