How do you replace or delete characters from a string with python?

I’m wondering how to replace or remove specific letters in a string with python.
I’m working on a level editor where the script would create the level layout from a grid of characters in a string.
Especially, how to remove spaces and tabs.

Hi,
To replace strings, use string.replace()
First argument for stating the desired strings that you want to remove.
Second argument for stating the desired replacement string(s)

# Replace method
TEXT = "PLACEHOLDER|TEXT|PLACEHOLDER"
print(TEXT.replace("PLACEHOLDER", "EMPTY"))

To remove strings, use string.strip() or string.replace (But have the second argument string(s) set to a empty string.

First method.

# Remove method (1)
TEXT = "PLACEHOLDER|TEXT|PLACEHOLDER"
print(TEXT.strip("PLACEHOLDER"))

Second method.

# Remove method (2)
TEXT = "PLACEHOLDER|TEXT|PLACEHOLDER"
print(TEXT.replace("PLACEHOLDER", ""))
1 Like

This works exactly as I needed, thank you.

1 Like

Just shimming in to mention that strip only remove stuff in the front or back of the string, but not in the middle. It is usually used to remove whitespace surrounding a string.

get fancy with re.sub

1 Like