There is a string, for example. EXAMPLE
.
How can I remove the middle character, i.e., M
from it? I don't need the code. I want to know:
- Do strings in Python end in any special character?
- Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string and not copying the middle character?
Strings are immutable in Python so both your options mean the same thing basically.
Here's what I did to slice out the "M":
Use the
translate()
method:This is probably the best way:
Don't worry about shifting characters and such. Most Python code takes place on a much higher level of abstraction.
If you want to delete/ignore characters in a string, and, for instance, you have this string,
"[11:L:0]"
from a web API response or something like that, like a CSV file, let's say you are using requests
loop and get rid of unwanted chars:
Optional split, and you will be able to read values individually:
Now accessing each value is easier:
This will print
To delete a
char
or asub-string
once (only the first occurrence):NOTE: Here
1
can be replaced with anyint
for the number of occurrence you want to replace.