How i can remove letter from the position
string1 = 'BPBPBPPPBPPPPPPBBBBPPBPBPPBPPPPBBPBPPBPBPP'
letter_4 = string1[3]
new_text = re.sub(letter_4,'', string1)
The resault is BBBBBBBBBBBBBBBB
The result I want is to remove only the letter number 4, which is 'P'
CodePudding user response:
As Carlos Horn said in his comment, to remove a character at index n
in a string, you can simply use
st = "Hello there"
n = 6
st = st[:n] st[n:]
In this case specifically:
string1 = 'BPBPBPPPBPPPPPPBBBBPPBPBPPBPPPPBBPBPPBPBPP'
n = 3
new_text = string1[:n] string[n 1:]
CodePudding user response:
Python strings are immutable, so you cannot update them in place. There are several ways to remove it. Which way is best depends on your other code and how you will "plug" it in your algorithm. Maybe you could describe problem which you are solving.
- converting to list and back, slow on long strings, but readable, and you can do other edit operations on it
chars = list(string1)
chars[3:4] = []
new_text = ''.join(chars)
- joining two substring without unwanted position as @Carlos commented,
new_text = string1[:3] string1[4:]
- replacing only first instance, not exactly what you asked, but good to know
new_text = string1.replace('B', '', count=1)
Hope you can build you algorithm with some of these.