Best method for Building Strings in Python
Your question is about Python 2.7, but it is worth note that from Python 3.6 onward we can use f-strings:
place = 'world'
f'hallo {place}'
'hallo world'
This f
prefix, called a formatted string literal or f-string, is described in the documentation on lexical analysis
You have two options here:
- Use the string
.join()
method:" ".join(["This", "is", "a", "test"])
- Use the percent operator to replace parts of a string:
"%s, %s!" % ("Hello", "world")
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'