在逗号分隔的lis中搜索字符串

2024-10-02 18:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

列表显示在中用户日志文件。你知道吗

我已经使用python从用户日志文件。你知道吗

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

我的代码:

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])

我的输出:

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

因此,我没有得到任何东西来使用Python搜索名称并检索关于名称的ROLL NO。你知道我该怎么解决这个问题吗?你知道吗


Tags: 文件用户newdatastudentlinesprintroll
2条回答

你就快到了-你把行拆分成了它的组件,现在你只需要比较名称和搜索值:

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

你能做到的。你知道吗

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.

相关问题 更多 >