简体   繁体   中英

Searching for string in comma separated list

The list is present in User.log file.

I have extracted the list line by line using python from User.log file.

SHRAMIK,STUDENT,CSE,34, 
KESHAV,TEACHER,MECH,12
list = ['SHRAMIK,STUDENT,CSE,34', 'KESHAV,TEACHER,MECH,12']
search_value = "SHRAMIK"

My CODE:

with open('User.Log') as f:
    lines = f.read().splitlines()
    print(type(lines))
    data = lines[0].split(",")
    print("NEW LINES =============== >" ,lines)
    print("NEW DATA =============== >" , data , "Roll No FROM LIST IS :", data[3])

MY OUTPUT:

('NEW LINES =============== >', ['SHRAMIK,STUDENT,CSE,34', 'KESHAV,TEACHER,MECH,12'])
('NEW DATA =============== >', ['SHRAMIK,STUDENT,CSE,34'], 'Roll No FROM LIST IS :', '34'

So I am not getting anything to the point to search for the NAME and retrieve the ROLL NO with respect to the NAME using Python. Please do you have any idea how should I solve this issue?

You're almost there - you split the line to its components, now you just need to compare the name to the search value:

with open('User.Log') as f:
    for line in f:
        parts = line.split(',')
        if line[0] == search_value:
             print('Rollno is ' + line[3])
             break;

You can do this.

with open('User.Log') as f:
    for data in f:
        if data.split(',')[0] == searchKey:
            print("Found student with Roll number {}".format(data.split(',')[3])
            break
    else:
        print("not found with name {}".format(searchKey))  #else is outside the for loop 

The else block just after for/while is executed only when the loop is NOT terminated by a break statement.

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