-2

In a specific string I would be given start position and length.

for eg input string "abcdefgh" . start position : 3 and length :2. I want to replace characters with space

so the output string should " ab efgh" . how can i do that in python?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    Possible duplicate of [Understanding Python's slice notation](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) – Patrick Artner Oct 31 '18 at 20:24
  • strings are immutable and iterable - you need to slice it and put the amount of spaces in it – Patrick Artner Oct 31 '18 at 20:25
  • 2
    why should the output string start with a space? why are there 3 spaces inside but only 2 characters removed? – Patrick Artner Oct 31 '18 at 20:31
  • strings are immutable meaning if you slice and append some characters you are actually creating a new string object. Also, your expected output is a little confusing. Edit your post with your attempt as well to show what you have tried and not worked for you – mad_ Oct 31 '18 at 20:47

1 Answers1

0

If you start with

a="abcdefgh"
start=3
length=2

Then you can slice your string by using indexes and add your chosen number of spaces in the middle this way:

b=a[:start-1] + " "*length + a[start-1+length:]
print(b)

This outputs:

ab  efgh

This answer on slicing mentioned by Patrick above gives a pretty good overview.

millibyte
  • 77
  • 4