1

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

2
  • 1
    I think we need more information about the pattern of the data. A solution can be found for the data provided, but it could be that it doesn't work for any other case you might have. Commented Jan 17, 2014 at 13:27
  • 2
    1, 7, 3, and 0 are not letters. Also, don't name a list list, that shadows a builtin type. Commented Jan 17, 2014 at 13:34

4 Answers 4

5
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
Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

Downvoter: How can I improve the answer? If there's anything wrong, please let me know.
1

Well you could do like this

_2nd = lsit[0][1]

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.