I am trying to remove all of a specific character from a string. I have been using String.Replace
, but it does nothing, and I don't know why. This is my current code:
if (Gamertag2.Contains("^")) { Gamertag2.Replace("^" + 1, ""); }
This just leaves the string as it was before. Can anyone please explain to me as to why?
Example 1: Input: s = "daabcbaabcbc", part = "abc" Output: "dab" Explanation: The following operations are done: - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".
Using translate(): translate() is another method that can be used to remove a character from a string in Python. translate() returns a string after removing the values passed in the table. Also, remember that to remove a character from a string using translate() you have to replace it with None and not "" .
Python Remove Character from String using replace() If we provide an empty string as the second argument, then the character will get removed from the string. Note that the string is immutable in Python, so this function will return a new string and the original string will remain unchanged.
You must assign the return value of String.Replace
to your original string instance:
hence instead of(no need for the Contains check)
if (Gamertag2.Contains("^")) { Gamertag2.Replace("^" + 1, ""); }
just this(what's that mystic +1
?):
Gamertag2 = Gamertag2.Replace("^", "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With