[英]Python How to find a specific string from a list and print that line out?
I have a list and in that list, I am trying to find a specific string in that list by asking the user to enter in a word and I will print that word and the line that it is from我有一个列表,在该列表中,我试图通过要求用户输入一个单词来查找该列表中的特定字符串,然后我将打印该单词以及它来自的行
This is one list这是一份清单
new_list = ['An American', 'Barack Obama', '4.7', '18979'],
['An Indian', 'Mahatma Gandhi', '4.7', '18979'],
['A Canadian', 'Stephen Harper', '4.6', '19234']
For example, if I can input "ste" in the string and it should print the 3rd line as "Stephen Harper" is in there例如,如果我可以在字符串中输入“ste”并且它应该打印第三行,因为“Stephen Harper”在那里
I tried this but it did not work:我试过这个,但没有用:
find_String = input("Enter a string you're looking for: ")
if find_String in new_list:
print(new_list)
else:
print("String not found!")
arr = ['An American', 'Barack Obama', '4.7', '18979', 'An Indian', 'Mahatma Gandhi', '4.7', '18979',
'A Canadian', 'Stephen Harper', '4.6', '19234']
inputStr = input("Enter String: ")
for val in arr:
if inputStr in val:
print(val);
This isn't null safe这不是空安全
This will also print all the values that have the specified substring, if you want only the first, add a break to the end of the if condition这还将打印具有指定子字符串的所有值,如果您只想要第一个,请在 if 条件的末尾添加一个中断
Well it doesn't work because of the following reasons :-好吧,由于以下原因,它不起作用:-
list
is only holding one list object, the first one, the rest 2 are not in the variable.变量list
只保存一个列表对象,第一个,其余 2 个不在变量中。if
statement, for it has to iterate through the 3 lists within the list
variable.它不能用简单的if
语句完成,因为它必须遍历list
变量中的 3 个列表。The following code will work :-以下代码将起作用:-
L1 = [['An American', 'Barack Obama', '4.7', '18979'],
['An Indian', 'Mahatma Gandhi', '4.7', '18979'],
['A Canadian', 'Stephen Harper', '4.6', '19234']]
find_String = input("Enter a string you're looking for: ")
for data in L1:
for string in data:
if find_String.lower() in string.lower():
print(data)
exit(0)
else:
print("String not found!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.