Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip all but first 5 characters - Python [duplicate]

Tags:

Possible Duplicate:
Is there a way to substring a string in Python?

I have a string in the form 'AAAH8192375948'. How do I keep the first 5 characters of this string, and strip all the rest? Is it in the form l.strip with a negative integer? Thanks.

like image 898
bac Avatar asked Jul 25 '11 16:07

bac


People also ask

How do I remove the first 5 characters from a string in Python?

Use Python to Remove the First N Characters from a String Using Regular Expressions. You can use Python's regular expressions to remove the first n characters from a string, using re's . sub() method. This is accomplished by passing in a wildcard character and limiting the substitution to a single substitution.

Can you strip multiple characters Python?

To strip multiple characters in Python, use the string strip() method. The string strip() method removes the whitespace from the beginning (leading) and end (trailing) of the string by default. The strip() method also takes an argument, and if you pass that argument as a character, it will remove it.

How do I remove certain letters from a string in Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.


1 Answers

A string in Python is a sequence type, like a list or a tuple. Simply grab the first 5 characters:

 some_var = 'AAAH8192375948'[:5]  print some_var # AAAH8 

The slice notation is [start:end:increment] -- numbers are optional if you want to use the defaults (start defaults to 0, end to len(my_sequence) and increment to 1). So:

 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] 

strip removes a character or set of characters from the beginning and end of the string - entering a negative number simply means that you are attempting to remove the string representation of that negative number from the string.

like image 109
Sean Vieira Avatar answered Oct 19 '22 17:10

Sean Vieira