![](/img/trans.png)
[英]How to check check if a string contains a specific character(s) using range() functions and bools in Python?
[英]Python: How to check if the string contains number from a specific range
我的字符串很長; 它們基本上是文件名。 格式如下:
["abcdedf_023.txt",
"foeoioo_011.txt",
"sdjskdsjd_3131.txt",
"dsdsdsrer_044.txt",
"rgfbfgrt_12.txt"]
等等。
我需要過濾掉結尾處包含大於15
數字的名稱。 因此,使用上述輸入,所需的輸出為:
["abcdedf_023.txt",
"sdjskdsjd_3131.txt",
"dsdsdsrer_044.txt"]
該數字(15)不確定,由用戶提供作為輸入。
像下面嗎? 只需使用\\d+
搜索號碼?
[i for i in l if int(re.search('\d+', i).group(0)) > 15]
演示:
["abcdedf_023.txt", "sdjskdsjd_3131.txt", "dsdsdsrer_044.txt"]
您還可以搜索_(\\d+).txt
(使用()
來捕獲類似的數字):
[i for i in f if int(re.search('_(\d+).txt', i).group(1)) > 15]
要在文件中刪除"abc122dedf_01.txt"
的內容(如果不需要的話)。
如果只需要文件名中的最后兩個數字,例如從1203
獲取03
:
[i for i in f if int(re.search('\d+', i).group(0)[-2:]) > 15]
我會用split
>>> l = ["abcdedf_023.txt",
"foeoioo_011.txt",
"sdjskdsjd_3131.txt",
"dsdsdsrer_044.txt",
"rgfbfgrt_12.txt"]
>>> [i for i in l if int(i.split('.')[0].split('_')[-1]) > 15 ]
['abcdedf_023.txt', 'sdjskdsjd_3131.txt', 'dsdsdsrer_044.txt']
將上面的列表理解中的15
替換為實際包含要檢查的數字的變量。請注意,該變量必須為interger類型,或者在條件檢查期間將其轉換為int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.