简体   繁体   中英

Extract only numeric value from string within Python list

Hi what im trying to do is to extract only number from string within certain list item however the result is printed with brackets [ ]. How to remove them? The result Im getting is [2000] instead of 2000.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#opening txt file to extract data
import io

with io.open("testmodi.txt", "r", encoding="cp1250") as file:
     ocr_results = [line.strip() for line in file]

#spliting into list     
for line in ocr_results:
    print("[" + line + "]")



class overeview_mth:
 def __init__(self):
    self.closest_string = "Opis"
    self.distance_between_closest_string_and_matching_index = + 1
    self.every_matching_index_list_within_ocr_results = [i for i, x in enumerate(ocr_results) if x == self.closest_string]
    self.number_of_string_occurence_within_ocr_results = len(self.every_matching_index_list_within_ocr_results)
    self.matching_index = int(self.every_matching_index_list_within_ocr_results[self.number_of_string_occurence_within_ocr_results -1] + self.distance_between_closest_string_and_matching_index)



#for testing
target_index = overeview_mth()

print([int(s) for s in ocr_results[(target_index.matching_index)].split() if s.isdigit()])

If you want each of the list values printed separately, you need to take them out of the list, as Juanpa suggested. The code would be something like this, adapting from yours:

for s in ocr_results[(target_index.matching_index)].split():
    if s.isdigit:
        print (int(s))

Does that work for you? Your original print did some lovely extra work to put all of the results into a list, but that doesn't seem to be what you ultimately need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM