Strip all but first 5 characters - Python
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Is there a way to substring a string in Python?
我有一个"aaah8192375948"形式的字符串。如何保留这个字符串的前5个字符,并去掉其余所有字符?它是L.Strip形式的负整数吗?谢谢。
python中的字符串是序列类型,如列表或元组。只需抓住前5个字符:
1 2 | some_var = 'AAAH8192375948'[:5] print some_var # AAAH8 |
切片表示法是
1 2 3 4 5 6 7 8 9 10 | sequence = [1,2,3,4,5,6,7,8,9,10] # range(1,11) sequence[0:5:1] == sequence[0:5] == sequence[:5] # [1, 2, 3, 4, 5] sequence[1:len(sequence):1] == sequence[1:len(sequence)] == sequence[1:] # [2, 3, 4, 5, 6, 7, 8, 9, 10] sequence[0:len(sequence):2] == sequence[:len(sequence):2] == sequence[::2] # [1, 3, 5, 7, 9] |
你听说过切片吗?
1 2 3 4 5 6 7 8 9 10 11 | >>> # slice the first 5 characters >>> first_five = string[:5] >>> >>> # strip the rest >>> stripped = string[5:].strip() >>> >>> # in short: >>> first_five_and_stripped = string[:5], string[5:].strip() >>> >>> first_five_and_stripped ('AAAH8', '192375948') |
我假设您的意思不仅仅是"去掉前5个字符以外的所有内容",而是"保留前5个字符,在其余的字符上运行strip()"。
1 2 3 4 5 | >>> x = 'AAH8192375948' >>> x[:5] 'AAH81' >>> x[:5] + x[5:].strip() 'AAH8192375948' |