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?
Asked
Active
Viewed 172 times
1

Shengen
- 73
- 5
-
3this is trivial in python using slicing. what have you tried? – Mike Corcoran Jul 23 '13 at 20:29
-
Maybe you could give us a more detailed description of your problem. There are several ways for achieving this, so it's a bit unclear what would be best in your case ... – Simon Steinberger Jul 23 '13 at 20:30
-
1Strings are immutable, so you need to construct a *new* string. Use slicing. – Martijn Pieters Jul 23 '13 at 20:30
2 Answers
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,776
- 4
- 32
- 52
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'
>>>