打印用户输入的第一个字母的名称--Python

时间:2016-12-21 18:23:15

标签: python arrays string list

letter = input("Enter a letter to show that particular country: ")
output_names = [name for name in Country if (name[0] in letter)]
print(output_names)

我有这个,我的.txt文件有点长,错误显示是 - " IndexError:字符串索引超出范围"。 我怎样才能使它发挥作用?

2 个答案:

答案 0 :(得分:0)

您可以使用多种因素组合对列表推导进行小编辑。

  1. 空的东西是假的,例如列表/字典/空字符串

    interface ICustomer{ id: number; name: string; age: number city: string } let customers: Array<ICustomer>; function generateCustomers(): void { let id: number = 0; createCustomer("Drew", id++, 22, "Glassboro"); createCustomer("Mike", id++, 40, "Rineyville"); createCustomer("Justin", id++, 19, "Jonesboro"); createCustomer("Alex", id++, 15, "Paulsboro"); createCustomer("Phil", id++, 32, "Glassboro"); } function getAllCustomers(): ICustomer[]{ generateCustomers(); return customers; } function createCustomer(name:string,id:number,age:number,city:string): void { let newCustomer:ICustomer = {id:id,name:name,age:age,city:city}; customers.push(newCustomer); } const allCustomers = getAllCustomers; function getCustomerInformation(id:number): ICustomer { for (let customer of allCustomers()) { if(customer.id === id){ return customer; } } return null; } console.log(getCustomerInformation(1));

    not exists

    SELECT applicantWarehouse.first , applicantWarehouse.last , applicantWarehouse.title , applicantWarehouse.ID , jobTracking.applicantID , jobTracking.jobID FROM jobTracking INNER JOIN applicantWarehouse ON jobTracking.applicantID = applicantWarehouse.ID WHERE Degree="MD" AND NOT EXISTS ( SELECT 1 FROM jobTracking j WHERE j.jobID = 56 AND j.applicantID = applicantWarehouse.ID )

    bool('')

  2. 逻辑运算符Out[1]: False将短路。这意味着在这种情况下,如果它在第一次测试时看到bool('a'),它将不会尝试后续测试。

  3. 将它们放在一起,我们可以避免尝试索引空字符串。

    Out[2]: True

答案 1 :(得分:0)

只是这样做:

print [name for name in Country if name.lower().startswith(letter.lower())]