-4

How can I change the first 5 characters of a string in python? Is there any library or method for this?

An example:

Input:

str1: ABCSDASFA213123

EXPECTED OUTPUT:

str2: XXXXXASFA213123
cosmos-1905-14
  • 783
  • 2
  • 12
  • 23
  • 3
    What did you try so far? any example of expected input/output?? – ncica Nov 11 '21 at 19:16
  • 1
    May be worth noting, strings are immutable; you can reassign a variable to reference a new string (which may not be relevant to your concern). – Joshua Voskamp Nov 11 '21 at 19:18
  • Just added expected output here – cosmos-1905-14 Nov 11 '21 at 19:18
  • There are many tutorials on how to update/replace characters in Python strings. Like [this one](https://tutorial.eyehunts.com/python/python-replace-character-in-a-string-by-index-example-code/). Why are you asking here? Did you try any tutorials and they didn't work? – Random Davis Nov 11 '21 at 19:18
  • Strings are immutable, so in a strict sense, you cannot _change_ them. The usual way to do this is to assemble a _new_ string that has the desired contents. – John Gordon Nov 11 '21 at 19:18

1 Answers1

5

Slice off the first five characters, and replace them with whatever you like:

new_str = 'X' * 5 + old_str[5:]
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • I didn't know we could do this `'X' * 5` in python. I appreciate your answer – cosmos-1905-14 Nov 11 '21 at 20:33
  • @cosmos-1905-14: Yep, all sequences can be multiplied to produce that many repetitions of the sequence. I could've type `'XXXXX'`, but I kinda enjoy making the intended repetition count explicit when I can. – ShadowRanger Nov 11 '21 at 20:42