-1

How to replace numerical with character set in the string without using numpy or pandas in python?

Example:

Original String = A student has secured 90% of marks whose roll number is 2012684954

Updated string = A student has secured 90% of marks whose roll number is 201HKM4954

James Z
  • 12,209
  • 10
  • 24
  • 44
  • You could use the replace function – Exania Jun 02 '22 at 10:02
  • You could just the `str.replace` method and loop through all the replacements. Replacements can be defined in a dictionary as a key: value pair. https://stackoverflow.com/questions/9452108/how-to-use-string-replace-in-python-3-x – Tzane Jun 02 '22 at 10:03
  • Does this answer your question? [How to use string.replace() in python 3.x](https://stackoverflow.com/questions/9452108/how-to-use-string-replace-in-python-3-x) – Mortz Jun 02 '22 at 10:05

2 Answers2

1

As indicated in the comments you can use replace function and a dictionary to store the replacements:

string = 'A student has secured 90% of marks whose roll number is 2012684954'

replacements = {
    '268': 'HKM',
    '90': 'AA'
}

for rep in replacements:
    string = string.replace(rep, replacements[rep])

print(string)
Dan Constantinescu
  • 1,426
  • 1
  • 7
  • 11
0

Depending on the requirements, here is something you can use:

  1. regular expressions (re.sub)
  2. any of the built-in python string methods (like str.replace)
enoted
  • 577
  • 7
  • 21