Reputation:
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
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
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
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