140

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?

tkbx
  • 15,602
  • 32
  • 87
  • 122
  • 5
    better 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 Answers5

261
>>> text = 'lipsum'
>>> text[3:]
'sum'

See the official documentation on strings for more information and this SO answer for a concise summary of the notation.

jamylak
  • 128,818
  • 30
  • 231
  • 230
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
phoenix
  • 7,988
  • 6
  • 39
  • 45
Ken A
  • 371
  • 2
  • 4
  • 3
    I 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
  • 11
    Note 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
  • 1
    This 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
  • 1
    Neither 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