簡體   English   中英

如何使用 Python 從字符串中提取某些字母

[英]How to extract certain letters from a string using Python

我有一個字符串 'A1T1730'

我需要從中提取第二個字母和最后四個字母。 例如,我需要從“A1T1730”中提取“1”和“1730”。 我不確定如何在 Python 中執行此操作。

我現在有以下內容,它分別從字符串中提取每個字符,所以有人可以根據上述需要幫助我更新它。

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

這給了我 A, 1, T, 1, 7, 3, 0 的結果

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

輸出量

11730

如果要將它們提取到不同的變量中,則可以執行以下操作

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

輸出量

1 1730

filterstr.isdigit一起str.isdigit (作為未綁定方法形式):

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

如果要分隔數字,請使用正則表達式(請參見re.findall ):

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

如果數字的位置固定,請使用fourtheye的解決方案。


順便說一句,不要使用list作為變量名。 它隱藏了內置list功能

那么你可以這樣做

_2nd = lsit[0][1]

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

您可以使用isdigit()函數。 如果該字符是數字,則返回true,否則返回false:

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

我希望這有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM