1

For example, my String = 'xx22xx_1x_xxxx-xxxx', x can be any letters. Now I want to delete the first two positions letters xx and seventh position 1, in order to get a NewString = '22xx_x_xxxx-xxxx'. Any function to erase letters at specific positions?

Shengen
  • 73
  • 5

2 Answers2

5

You want to implement slicing! It is not just applicable to strings.

Example from this question: Is there a way to substring a string in Python?

>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'

To Answer your question do this!

Removing the first two "xx"

NewString = String[2:]

Removing the 1

NewString = NewString[:5]+NewString[7:]
Community
  • 1
  • 1
Kirk Backus
  • 4,568
  • 4
  • 28
  • 51
3

This will do it:

def erase(string, positions):
    return "".join([y for x,y in enumerate(string) if x not in positions])

demo:

>>> s='xx22xx_1x_xxxx-xxxx'
>>> erase(s, (0,1,7))
'22xx_x_xxxx-xxxx'
>>>