user1345260
user1345260

Reputation: 2249

How to extract certain letters from a string using Python

I have a string 'A1T1730'

From this I need to extract the second letter and the last four letters. For example, from 'A1T1730' I need to extract '1' and '1730'. I'm not sure how to do this in Python.

I have the following right now which extracts every character from the string separately so can someone please help me update it as per the above need.

list = ['A1T1730']  
for letter in list[0]:  
      print letter  

Which gives me the result of A, 1, T, 1, 7, 3, 0

Upvotes: 1

Views: 15788

Answers (4)

Rahul Biswas
Rahul Biswas

Reputation: 79

Well you could do like this

_2nd = lsit[0][1]

# last 4 characters
numbers = list[0][-4:]

Upvotes: 1

MarcoGarzini
MarcoGarzini

Reputation: 84

You can use the function isdigit(). If that character is a digit it returns true and otherwise returns false:

list = ['A1T1730']  
for letter in list[0]:
    if letter.isdigit() == True:
        print letter, #The coma is used for print in the same line 

I hope this useful.

Upvotes: 0

falsetru
falsetru

Reputation: 369054

Using filter with str.isdigit (as unbound method form):

>>> filter(str.isdigit, 'A1T1730')
'11730'
>>> ''.join(filter(str.isdigit, 'A1T1730')) # In Python 3.x
'11730'

If you want to get numbers separated, use regular expression (See re.findall):

>>> import re
>>> re.findall(r'\d+', 'A1T1730')
['1', '1730']

Use thefourtheye's solution if the positions of digits are fixed.


BTW, don't use list as a variable name. It shadows builtin list function.

Upvotes: 5

thefourtheye
thefourtheye

Reputation: 239453

my_string = "A1T1730"
my_string = my_string[1] + my_string[-4:]
print my_string

Output

11730

If you want to extract them to different variables, you can just do

first, last = my_string[1], my_string[-4:]
print first, last

Output

1 1730

Upvotes: 5

Related Questions