tkbx
tkbx

Reputation: 16275

Removing first x characters from string?

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?

Upvotes: 148

Views: 361341

Answers (5)

U13-Forward
U13-Forward

Reputation: 71570

Use del.

Example:

>>> text = 'lipsum'
>>> l = list(text)
>>> del l[3:]
>>> ''.join(l)
'sum'

Upvotes: 4

Ken A
Ken A

Reputation: 401

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

Upvotes: 27

Pratik Jaswant
Pratik Jaswant

Reputation: 27

Example to show last 3 digits of account number.

x = '1234567890'   
x.replace(x[:7], '')

o/p: '890'

Upvotes: 1

jamylak
jamylak

Reputation: 133554

>>> 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.

Upvotes: 269

tkbx
tkbx

Reputation: 16275

>>> x = 'lipsum'
>>> x.replace(x[:3], '')
'sum'

Upvotes: 13

Related Questions