Replace/Translate Characters in a String

Remove characters from text using TRANSLATE function (replace them with empty strings)

You can try the following query:

DECLARE @text AS VARCHAR(20) = 'abr_akad-ab#ra';
SELECT REPLACE(TRANSLATE(@text, '_-#', '###'), '#', '')

it will return the output as abrakadabra

Working demo on db<>fiddle

Replace / translate characters in a string

You can create from and to vectors:

from <- c('a','b','c','d','e','f')
to <- c('h','i','j','k','l','m')

and then vectorialize the gsub function:

gsub2 <- function(pattern, replacement, x, ...) {
for(i in 1:length(pattern))
x <- gsub(pattern[i], replacement[i], x, ...)
x
}

Which gives:

> df <- data.frame(var1 = c("aabbcdefg", "aabbcdefg"))
> df$var1 <- gsub2(from, to, df$var1)
> df
var1
1 hhiijklmg
2 hhiijklmg

SQL Replace multiple different characters in string

You just need to daisy-chain them:

REPLACE(REPLACE(T2.[ShipToCode], '&', 'and'), ',', '')

Replace special characters in a string in Python

str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:

removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})

This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space.

Replace (translate) one char to many

That's my "barbarian", but effective solution. it's main part:

res :=
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
p_txt,
CHR(0),
'\0x00'
),
CHR(1),
'\0x01'
),
CHR(2),
'\0x02'
),
CHR(3),
'\0x03'
),
CHR(4),
'\0x04'
),
CHR(5),
'\0x05'
),
CHR(6),
'\0x06'
),
CHR(7),
'\0x07'
),
CHR(8),
'\0x08'
),
CHR(9),
'\0x09'
),
CHR(10),
'\0x0A'
),
CHR(11),
'\0x0B'
),
CHR(12),
'\0x0C'
),
CHR(13),
'\0x0D'
),
CHR(14),
'\0x0E'
),
CHR(15),
'\0x0F'
),
CHR(16),
'\0x10'
),
CHR(17),
'\0x11'
),
CHR(18),
'\0x12'
),
CHR(19),
'\0x13'
),
CHR(20),
'\0x14'
),
CHR(21),
'\0x15'
),
CHR(22),
'\0x16'
),
CHR(23),
'\0x17'
),
CHR(24),
'\0x18'
),
CHR(25),
'\0x19'
),
CHR(26),
'\0x1A'
),
CHR(27),
'\0x1B'
),
CHR(28),
'\0x1C'
),
CHR(29),
'\0x1D'
),
CHR(30),
'\0x1E'
),
CHR(31),
'\0x1F'
);

How do I replace characters in a string in Python?

"".join(code.get(k, k) for k in str)

would also work in your case.

code.get(k, k) returns code[k] if k is a valid key in code; if it isn't, it returns k itself.

Efficiently replace all accented characters in a string?

I can't speak to what you are trying to do specifically with the function itself, but if you don't like the regex being built every time, here are two solutions and some caveats about each.

Here is one way to do this:

function makeSortString(s) {
if(!makeSortString.translate_re) makeSortString.translate_re = /[öäüÖÄÜ]/g;
var translate = {
"ä": "a", "ö": "o", "ü": "u",
"Ä": "A", "Ö": "O", "Ü": "U" // probably more to come
};
return ( s.replace(makeSortString.translate_re, function(match) {
return translate[match];
}) );
}

This will obviously make the regex a property of the function itself. The only thing you may not like about this (or you may, I guess it depends) is that the regex can now be modified outside of the function's body. So, someone could do this to modify the interally-used regex:

makeSortString.translate_re = /[a-z]/g;

So, there is that option.

One way to get a closure, and thus prevent someone from modifying the regex, would be to define this as an anonymous function assignment like this:

var makeSortString = (function() {
var translate_re = /[öäüÖÄÜ]/g;
return function(s) {
var translate = {
"ä": "a", "ö": "o", "ü": "u",
"Ä": "A", "Ö": "O", "Ü": "U" // probably more to come
};
return ( s.replace(translate_re, function(match) {
return translate[match];
}) );
}
})();

Hopefully this is useful to you.


UPDATE: It's early and I don't know why I didn't see the obvious before, but it might also be useful to put you translate object in a closure as well:

var makeSortString = (function() {
var translate_re = /[öäüÖÄÜ]/g;
var translate = {
"ä": "a", "ö": "o", "ü": "u",
"Ä": "A", "Ö": "O", "Ü": "U" // probably more to come
};
return function(s) {
return ( s.replace(translate_re, function(match) {
return translate[match];
}) );
}
})();

str.translate vs str.replace - When to use which one?

They serve different purposes.

translate can only replace single characters with arbitrary strings, but a single call can perform multiple replacements. Its argument is a special table that maps single characters to arbitrary strings.

replace can only replace a single string, but that string can have arbitrary length.

>>> table = str.maketrans({'f': 'b', 'o': 'r'})
>>> table
{102: 'b', 111: 'r'}
>>> 'foo'.translate(table)
'brr'
>>> 'foo'.translate(str.maketrans({'fo': 'ff'}))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: string keys in translate table must be of length 1
>>> 'foo'.replace('fo', 'ff')
'ffo'

Replace multiple (special) characters - most efficient way?

For an efficient solution you could use str.maketrans for this. Note that once the translation table is defined, it's onle a matter of mapping the characters in the string. Here's how you could do so:

symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+",
"=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]

Start by creating a dictionary from the symbols using dict.fromkeys setting a single space as value for each entry and create a translation table from the dictionary:

d = dict.fromkeys(''.join(symbols), ' ')
# {'`': ' ', ',': ' ', '~': ' ', '!': ' ', '@': ' '...
t = str.maketrans(d)

Then call the string translate method to map the characters in the above dictionary with an empty space:

s = '~this@is!a^test@'
s.translate(t)
# ' this is a test '

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