How to replace strings in a string

string replace
string replace python
string replace java
java string replace substring
java replace character in string at index
python replace character in string at index
string replace javascript
java replace substring at index

I have a text string. I need to decode the text string i.e, replace every character in the string with its counterpart and then read the message. How do I achieve this?

For example:

g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.

is encoded. I need to replace a's with c, b's with d ,etc. How do I do this within Python?

There is a problem when I do replace. When I do a replace all, I replace the replaced characters and that is not what I want. I want to replace one character at a time and decode the message.

Apparently string.maketrans() is the way to do it

>>> s = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
>>> from string import maketrans, ascii_lowercase
>>> T = maketrans(ascii_lowercase, ascii_lowercase[2:] + ascii_lowercase[:2])
>>> s.translate(T)
"i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url."

How to replace a substring of a string, Python String | replace(). replace() is an inbuilt function in Python programming language that returns a copy of the string where all occurrences of a substring is � Dim aString As String = Replace(TestString, "o", "i") Remarks. The return value of the Replace function is a string that begins at the position specified by Start and concludes at the end of the Expression string, with the substitutions made as specified by the Find and Replace values. The Compare argument can have the following values.

With Python 3, it's can also look like this.

import string

message = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq   ypc " \
          "dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq " \
          "rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu " \
          "ynnjw ml rfc spj."

table = str.maketrans(string.ascii_lowercase, string.ascii_lowercase[2:] + string.ascii_lowercase[:2])

print(message.translate(table))

Use str.maketrans(x[, y[, z]]) for mapping letter "each character in x, will be mapped to the character at the same position in y." The explain is from here.

Than for substring a-z string.ascii_lowercase [2:] look here.

Python String, var res = str.replace("Microsoft", "W3Schools"); The replace() method searches a string for a specified value, or a regular expression, and returns a new string� Java String replace() The java string replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence.. Since JDK 1.5, a new replace() method is introduced, allowing you to replace a sequence of char values.

I found a way to do this without maketrans(). I did not want to depend on such a function so I made my own. Took me hours to figure it out:

def shiftAll(text, shift):
    '''
    @param text - string of text to be shifted
    @param shift - the number of times to shift all letters; int value only

    In range 'a' to 'z' and 'A' to 'Z'
    Initializes empty string newText and appends the new shifted letters to it

    To shift right on th alphabet ex: a -> b or n -> y,
    enter a positive shift ex: 1, 2, 4
    To shift left on the alphabet ex: b -> a or q -> m,
    enter a negative shift ex: -2, -1, -5

    Handles:
    Error where index out of range
    Sum of shift and position is greater than 25 or less than 0
        ~Allows cases where the letter may be 'a'(j (position) == 0)
        but the shift is negative
        ~Allows cases where the letter may be 'z'(j (position) == 25)
        but the shift is positive

    returns newText
    '''
    alpha = "abcdefghijklmnopqrstuvwxyz"

    newText = ""
    for i in text:
        if ((i not in alpha) and (i not in alpha.upper())):
            newText += i        #only replaces alphabetical characters  

        for j in range(len(alpha)):     #26 letters, so positions 0-25
            if ((i == alpha[j]) or (i == alpha[j].upper())):
                while (j + shift > 25):    #to avoid index out of range error
                    shift -= 26
                while (j + shift < 0):   #to avoid index out of range error
                    shift += 26

                if(i == alpha[j].upper()): #because letters can be capital too
                    newText += alpha[j + shift].upper()
                else:
                    newText += alpha[j + shift]

    return newText

string = input("Enter anything with letters in it: ")
aShift = int(input("Enter how many places you want to shift the letters: ") 
#let's pretend the user will actually enter an int value in aShift
result = shiftAll(string, aShift)
print(result)

This works for any string and shifts all the letters in the string by the shift. The shift must be an int.

JavaScript String replace() Method, new − This is new substring, which would replace old substring. max − If this optional argument max is given, only the first count occurrences are replaced. Return� Replaces the portion of the string that begins at character pos and spans len characters (or the part of the string in the range between [i1,i2)) by new contents: (1) string

Using only built ins: converting to ASCII add 2 and back to chr.

In [1]: str = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
In [2]: res = ''

In [3]: for char in str:
    tmp = char
    if tmp.isalpha():
        tmp = ord(tmp)+2
        if tmp == 123: 
            tmp = 97
        if tmp == 124:
            tmp = 98
        tmp = chr(tmp)
    res += tmp
    ....:     

In [4]: res
Out[4]: "i hope you didnt translate it by hand. thats what computers are for. doing it in by hand is inefficient and that's why this text is so long. using string.maketrans() is recommended. now apply on the url."

Python String replace() Method, 2) Apart from String, you can also pass StringBuffer and StringBuilder to this method because they also implement the CharSequence interface. 3� replace() with a global regular expression. The string method string.replace(regExpSearch, replaceWith) searches and replaces the occurrences of the regular expression regExpSearch with replaceWith string. To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression:

a simple way to replace string on a string just using functions is:

def esta (elemento,lista):                      ##here create a function with element 
    for i in range (len(lista)):                ## in a list, and search the [i]
        if lista[i]==elemento:
            return i
    return -1

## principal program:

abc=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","a","b"]
a="g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
cad=""
cont=0
for car in a:
    if esta(car,abc)!=-1:
        cad=cad+abc[esta(car,abc)+2]
    else:
        cad=cad+car
print(cad)

if you need more explanation please contact me.

How to replace a substring in Java?, string (1), string& replace (size_t pos, size_t len, const string& str); string& replace (iterator i1, iterator i2, const string& str);. substring (2), string& replace (size_t� For example, if the string is “India is a developing country and India in the Asian Country”, from this string we need to replace the word “India” and changed to “Bharath”. This is possible by using the Replace function. In this article, we will show you how to replace strings in VBA coding. Replace Function

string::replace - C++ Reference, The following code creates a new string by replacing existing text with a The Replace method can replace either strings or single characters. Excel VBA Replace String. Excel VBA Replace looks for a substring within a list and replaces the substring with a second substring. When we use Excel VBA Replace Strings in Data there are some situations when we need to replace some character or a string from a sentence.

How to modify string contents, The syntax of replace() is: str.replace(old, new [, count]). replace() parameters. The replace() method can take maximum of 3 parameters: old - old substring you � REPLACE selects the first string based on the position. So you might replace four characters, starting with the sixth character in the string. SUBSTITUTE selects based on whether the string matches a predefined search. You might tell Excel to replace any instance of “2016” with “2017,” for example.

Python String replace(), This function returns a string or an array with all occurrences of search in subject replaced with the given replace value. If you don't need fancy replacing rules� Strings in .NET are immutable, they cannot be edited in-line. The closest you can get to in-line editing is to create a StringBuilder from a string, in-line fiddle with its contents and then get it to spit a string back out again.

Comments
  • Did you try string methods to replace the characters
  • @VishnuUpadhyay, I guess you haven't tried that way? :)
  • There are a lot of different possibilities. You can for instance create a new string iterating over yours or use it as a list. Be carefull if you try multiple replaces, you will have to ensure caracters cannot be replaced twice. Replace each character by _character_ to begin with, for instance.
  • str.translate() is best for this
  • @AshwiniChaudhary I guess he meant replace each b by a d.
  • you could also use based 26 and add 97 to the result, that might be a nicer solution. instead of the if statement.