问题:从字符串中删除前x个字符?

如何从字符串中删除前x个字符?例如,如果一个人有一个字符串lipsum,他们将如何删除前三个字符并得到结果sum

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?


回答 0

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

有关更多信息,请参见有关字符串的官方文档,有关符号的简要概述,请参见此SO答案。

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


回答 1

另一种方法(取决于您的实际需求):如果要弹出前n个字符并同时保存弹出的字符和修改后的字符串:

s = 'lipsum'
n = 3
a, s = s[:n], s[n:]
print(a)
# lip
print(s)
# sum

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

回答 2

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

回答 3

使用del

例:

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

Use del.

Example:

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

回答 4

示例显示帐号的后3位数字。

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

o/p: '890'

Example to show last 3 digits of account number.

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

o/p: '890'

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。