Replacing Instances of a Character in a String

Replacing instances of a character in a string

Strings in python are immutable, so you cannot treat them as a list and assign to indices.

Use .replace() instead:

line = line.replace(';', ':')

If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:

line = line[:10].replace(';', ':') + line[10:]

That'll replace all semi-colons in the first 10 characters of the string.

Replacing all instances of a character in a string using python

for i in range(s1):

Here s1 is a string and you are passing it to range function, which expects only numbers as parameters. That is the problem. You should be using the length of the string instead

for i in range(len(s1)):

But, your actual problem can be solved with str.replace, like this

s='IS GOING GO'
x='I'
y='a'
print(s.replace(x, y))

If you want to solve without str.replace, you can do it like this

s, result, x, y ='IS GOING GO', "", "I", "a"
for char in s:
if char == x:
result += y
else:
result += char
print(result)

Output

aS GOaNG GO

The same program can be written like this as well

s, result, x, y ='IS GOING GO', "", "I", "a"
for char in s:
result += y if char == x else char
print(result)

Replace all instances of character in string in typescript?

Your second example is the closest. The first problem is your variable name, new, which happens to be one of JavaScript's reserved keywords (and is instead used to construct objects, like new RegExp or new Set). This means that your program will throw a Syntax Error.

Also, since the dot (.) is a special character inside regex grammar, you should escape it as \.. Otherwise you would end up with result == "xxxxxxxxxxxxxxxxxx", which is undesirable.

let email = "my.email@email.com"

let re = /\./gi;

let result = email.replace(re, "x");

console.log(result)

Replacing a character within a string?

You have some typos, that makes your code unworkable.

Even if you fix this, x is a string, and string is not mutable.

You can just use str.replace.

 x = x.replace('.','-')

Python: Replace a character in string

def replacest1(string, st1, st2):
return string.replace(st1, st2)

Test:

replacest1("abcdefdcba", "c", "x")

results in:

"abxdefdxba"

Test:

replacest1("yyyyzzzz", "c", "x")

results in:

"yyyyzzzz"

Or much much much much better:

"abcdefdcba".replace("c", "x")

Please note that the function defined above is a 1:1 correspondence to the function demanded by the question. It is not a good practice to use string as an identifier. I'd strongly recommend not to use such kind of identifier.


A note: As the definition of such a function can be eliminated altogether as string.replace() still exists while it is deprecated the solution above will still contain the identifier string as used in the question. If the function couldn't be eliminated I'd use a different identifier here but as defining an own function isn't necessary at all anyway I let this identifier be as it is for now.


Here is a variant of how to implement that without the usage of string.replace():

def replaceCharacters(inputString, findChar, replaceChar):
assert isinstance(inputString, str)
assert isinstance(findChar, str)
assert len(findChar) == 1
assert isinstance(replaceChar, str)
assert len(replaceChar) == 1

buffer = ""
for c in inputString:
buffer += replaceChar if c == findChar else c
return buffer

A note: I prefer to use asserts in order to detect programming errors. If performance is not a big issue in your use case these asserts don't cause any trouble but prevent accidentally misusing a function like this: If you accidentally pass wrong parameters the asserts will fail and give you feedback immediately.

Replacing some characters in a string with another character

echo "$string" | tr xyz _

would replace each occurrence of x, y, or z with _, giving A__BC___DEF__LMN in your example.

echo "$string" | sed -r 's/[xyz]+/_/g'

would replace repeating occurrences of x, y, or z with a single _, giving A_BC_DEF_LMN in your example.



Related Topics



Leave a reply



Submit