How might one remove the first x characters from a string? For example, if one had a string lipsum
, how would they remove the first 3 characters and get a result of sum
?
Asked
Active
Viewed 3.1e+01k times
140

tkbx
- 15,602
- 32
- 87
- 122
-
5better example if the number of characters removed wasn't equal to the number of characters to remain. e.g. `"lipsumm"[3:] == "summ"` – Scott Pelak Mar 27 '17 at 14:43
5 Answers
24
Another way (depending on your actual needs): If you want to pop the first n characters and save both the popped characters and the modified string:
s = 'lipsum'
n = 3
a, s = s[:n], s[n:]
print(a)
# lip
print(s)
# sum
-
3I guess it's metaphorically "popped" but actually its just 2 different slices, no real popping – jamylak Feb 16 '18 at 02:51
13
>>> x = 'lipsum'
>>> x.replace(x[:3], '')
'sum'

tkbx
- 15,602
- 32
- 87
- 122
-
11Note that this is longer in code and will also take more time since you have to search for the substring before you replace it. Also: `>>> x = 'liplip'` `>>> x.replace(x[:3], '')` `''`. Sure you could fix this by having the third parameter (count) = 1 but it would still take longer. – jamylak Aug 04 '12 at 06:58
-
nah it's related to your answer so it belongs here. You can add count=1 to yours so that it still works btw – jamylak Aug 04 '12 at 07:11
4
Use del
.
Example:
>>> text = 'lipsum'
>>> l = list(text)
>>> del l[3:]
>>> ''.join(l)
'sum'

ClimateUnboxed
- 7,106
- 3
- 41
- 86

U13-Forward
- 69,221
- 14
- 89
- 114
-
1This doesn't work like you'd think `text = 'liplip'` `>>> text.lstrip(text[:3])` `''` because for one [`str.lstrip([chars])`](https://docs.python.org/3/library/stdtypes.html) _The chars argument is not a prefix; rather, all combinations of its values are stripped:_ – jamylak Jan 28 '20 at 11:39
-
1Neither of the solutions work eg. for `'liplip'`. In the second one `TypeError: 'str' object does not support item deletion` – jamylak Jan 28 '20 at 11:44
-
The 1st solution still does not work for the `'liplip'` example and the 2nd solution has overcomplicated everything. It's really hard to improve the simple inbuilt `text[3:]` – jamylak Jan 29 '20 at 11:45
-
hello U10-Forward, hope you don't mind, but I deleted the first solution posted as it was indeed incorrect for a general string. The solution deleted *all* instances of the first x characters if the string contained repeats and thus could cause a bug if used. – ClimateUnboxed Feb 19 '20 at 11:26
1
Example to show last 3 digits of account number.
x = '1234567890'
x.replace(x[:7], '')
o/p: '890'

Byron Coetsee
- 3,533
- 5
- 20
- 31

Pratik Jaswant
- 27
- 1
-
-
eg. `>>> x = '12345678901234567890'` `>>> x.replace(x[:7], 'xxxxxxx')` `'xxxxxxx890xxxxxxx890'` – jamylak Feb 16 '18 at 02:49
-
Also this doesn't even answer the question, you are replacing characters with `x`s instead of deleting them – jamylak Feb 16 '18 at 02:50