0

I have a dynamic string and I would like to remove the first attribute of an item it could find. I have the following code:

mystring = '''
item 1
item 2
*item 3
item 4
*item 5
'''
mystring = mystring.replace('*', '')
print((mystring))

This returns:

item 1
item 2
item 3
item 4
item 5

But I want it to only replace the first instance of * which in this case is *item 3. It should return:

item 1
item 2
item 4
*item 5

I basically want it to delete the first line that starts with * How can I go about doing this? Do I need to use regex?

0

1 Answer 1

0

Just add 1 in args -

mystring = mystring.replace('*', '',1)
print((mystring))
Sign up to request clarification or add additional context in comments.

2 Comments

But won't this just remove the *? How can I make it remove the entire line if it starts with *
use startswith function in if condition and if control goes inside the if condition replace the char and break, or use ^ at the start of regex.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.