从列表中格式化Python中的字符串

时间:2017-03-11 01:30:05

标签: python

class Employee:

def set_name(self, name):
    self.name = name

def set_IDnumber(self, IDnumber):
    self.IDnumber = IDnumber

def set_department(self, department):
    self.department = department

def set_jobTitle(self, jobTitle):
    self.jobTitle = jobTitle

def get_name(self):
    # Returns name
    return self.name

def get_IDnumber(self):
    # Returns IDnumber
    return self.IDnumber

def get_department(self):
    # Returns department
    return self.department

def get_jobTitle(self):
    # Returns job title
    return self.jobTitle

def make_list():
    # Declaring list for storing information
    employee_list = []
    print("Enter data for 3 employees")
    # Loop to loop through 3 employees info
    for i in range(1, 4):
        print('Employee ' + str(i))
        # Takes input for each object
        name = input('Enter employee name: ')
        idNumber = int(input('Enter employee ID number: '))
        department = input('Enter employee department: ')
        jobTitle = input('Enter job title: ')
        employee = Employee()
        # Sets information for each object
        employee.set_name(name)
        employee.set_IDnumber(idNumber)
        employee.set_department(department)
        employee.set_jobTitle(jobTitle)
        employee_list.append(employee)
    #Returns list for display
    return employee_list

def displayEmployees(list):
    # Declaring strings to be further manipulated for spacing purposes
    shopString = "CHRISTY'S SHOP EMPLOYEE REPORT"
    employeeString = "EMPLOYEE NAME"
    identifierString = "IDENTIFIER"
    departmentString = "DEPARTMENT"
    titleString = "TITLE"
    # String alignment
    print(shopString.center(70))
    print(employeeString + identifierString.center(40) + departmentString +     titleString.rjust(10))
    print("------------------" + "----------".center(30) + "----------".rjust(15) + "-----".rjust(10))
    for item in list:
        name = item.get_name()
        idNumber = item.get_IDnumber()
        department = item.get_department()
        jobTitle = item.get_jobTitle()
        print(name + idNumber.center(30) + department.rjust(15) + jobTitle.rjust(10))


def main():
    employees = make_list()
    displayEmployees(employees)

main()

这是我的计划。我试图格式化列表中的输出,如下所示:

enter image description here

如果有人可以帮助我,因为我发现由于列表中每个字符串的长度不同会抛弃对齐,因此必须有更好的方法来正确对齐信息。提前谢谢。

2 个答案:

答案 0 :(得分:0)

仅使用代码的相关部分和Format Specification Mini-Language,这是尝试:

# String alignment
print('{:^62}'.format(shopString))
print('{:<22}{:^20}{:<19}{:<15}'.format(employeeString, identifierString, departmentString, titleString))
print('{:<22}{:^20}{:<19}{:<15}'.format("------------------", "----------", "--------------", "-----------"))
for item in list:
    name = item.get_name()
    idNumber = item.get_IDnumber()
    department = item.get_department()
    jobTitle = item.get_jobTitle()
    print('{:<22}{:^20}{:<19}{:<15}'.format(name, idNumber, department, jobTitle))

输出:

                CHRISTY'S SHOP EMPLOYEE REPORT                
EMPLOYEE NAME              IDENTIFIER     DEPARTMENT         TITLE          
------------------         ----------     --------------     -----------    
Lily Thomas                   412         Administration     Manager        
John Doe                      132         Accounting         Accountant     
LaQuanda Shaka                321         Sales              Associate

当然,它可以直接修改并按照您的意愿进行格式化。

答案 1 :(得分:0)

最后的代码

我在代码中更改了一些内容。

首先,由于您没有使用不是加速器的方法,我使用了namedtuple而不是您的Employee类。如果你真的需要吸气剂和二传手(在课堂上)请大声朗读并让它沉入:

  

如果我必须拥有它们,那么我会将它们隐藏在财产后面。

(来自here的引用)。 财产我的意思是true pythonic properties。 但请尽量不要这样做,请参阅:this answer

其次,你必须检查用户是否给你一个好的类型(因此try-except)。

第三, 我使用了一种名为Format Specification Mini-Language (a.k.a. formatspec) 的东西。如果涉及字符串格式化,它确实很有用。

from collections import namedtuple

Employee = namedtuple('EmployeeRecord', 'name,idNumber,department,jobTitle')


def make_list():
    employees = []
    print("Enter data for 3 employees")
    i = 1
    while i < 4:
        print('Employee ' + str(i))

        name = input('Enter employee name: ')
        idNumber = input('Enter employee ID number: ')
        try:
            idNumber = int(idNumber)
        except ValueError:
            print("ID number is supposted to be integer")
            continue
        idNumber = int(idNumber)
        department = input('Enter employee department: ')
        jobTitle = input('Enter job title: ')
        employees.append(Employee(name,idNumber,department,jobTitle)) 
        i += 1
    return employees


def displayEmployees(list, titleFormat, recordFormat):
    shopString = "CHRISTY'S SHOP EMPLOYEE REPORT"
    print('{:^70}'.format(shopString))
    print(titleFormat.format("EMPLOYEE NAME", "IDENTIFIER", "DEPARTMENT", "TITLE"))
    print(titleFormat.format("------------------", "----------", "----------", "-----"))
    for item in list:
        name = item.name
        idNumber = item.idNumber
        department = item.department
        jobTitle = item.jobTitle
        print(recordFormat.format(name, idNumber, department, jobTitle))


def main():
    employees = make_list() # you can uncomment this line
    titleFormat = "{:<25}{:^15}{:<15}{:<10}"
    recordFormat = "{:<23}{:^19}{:<13}{:<10}"
    displayEmployees(employees, titleFormat, recordFormat)



def main2():
    e1 = Employee("name1", 1, "dep1", "title1")
    e2 = Employee("name2", 2, "dep2", "title2")
    e3 = Employee("name3", 3, "dep3", "title3")
    titleFormat = "{:<25}{:^15}{:<15}{:<10}"
    recordFormat = "{:<23}{:^19}{:<13}{:<10}"
    employees = [e1, e2, e3]
    displayEmployees(employees, titleFormat, recordFormat)

#main()
main2()

这是我从main2()得到的:

                    CHRISTY'S SHOP EMPLOYEE REPORT                    
EMPLOYEE NAME              IDENTIFIER   DEPARTMENT     TITLE     
------------------         ----------   ----------     -----     
name1                           1         dep1         title1    
name2                           2         dep2         title2    
name3                           3         dep3         title3   

如果您想了解有关python字符串格式here的更多信息,可以找到一个很棒的教程。

另外,我想推荐一篇关于java vs python python is not java

的文章