Gitzee Gitzee - 1 year ago 66
Python Question

Python: Use specific parts of a string (that looks like a list)

I have a text file (file.txt):


and I want to extract and sum the values paired with 'a' (or 'b' or 'c' or ...) so that:

totalValue = 20 # of 'a'
totalValue = 50 # of 'b'
totalValue = 20 # of 'c'

Note: text file is obviously not a list, even though it looks like it.

myFile = open("file.txt", "r")

while True:
theline = myFile.readline()
if "a" in theline: #Just used 'a' here as an example.
for char in theline:


That's roughly the code I have to read the file and check each line for 'a' (for example).

Thank you.

Answer Source
def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]

myFile = open("file.txt", "r")
content =
totalValue = 0

all_colon_indexes = find(content,':')

for i in range(0,len(content)):
    if content[i]==':':
        if content[i-1]=='a':  #THIS IS WHERE YOU SPECIFY 'a' or 'b' or 'c', etc
            index = i+1
            while True:
                if content[index].isdigit()==True:
            _value = int(value)
            totalValue = totalValue + _value

print totalValue


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download