pythonpython-2.7

Best method for Building Strings in Python


Does Python have a function to neatly build a string that looks like this:

Bob 100 Employee Hourly

Without building a string like this:

EmployeeName + ' ' + EmployeeNumber + ' ' + UserType + ' ' + SalaryType

The function I'm looking for might be called a StringBuilder, and look something like this:

stringbuilder(%s,%s,%s,%s, EmployeeName, EmployeeNumber, UserType, SalaryType, \n)

Solution

  • Normally you would be looking for str.join. It takes an argument of an iterable containing what you want to chain together and applies it to a separator:

    >>> ' '.join((EmployeeName, str(EmployeeNumber), UserType, SalaryType))
    'Bob 100 Employee Hourly'
    

    However, seeing as you know exactly what parts the string will be composed of, and not all of the parts are native strings, you are probably better of using format:

    >>> '{0} {1} {2} {3}'.format(EmployeeName, str(EmployeeNumber), UserType, SalaryType)
    'Bob 100 Employee Hourly'