Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 483
Dan O'Boyle Avatar asked Oct 30 '14 16:10

Dan O'Boyle


1 Answers

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'
like image 117
anon582847382 Avatar answered Oct 09 '22 18:10

anon582847382