Reputation: 3766
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)
Upvotes: 17
Views: 64999
Reputation: 17527
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
Upvotes: 18
Reputation: 107287
As EmployeeNumber
is a int object , or may you have may int amount your variables you can use str
function to convert them to string for refuse of TypeError
!
>>> ' '.join(map(str,[EmployeeName, EmployeeNumber,UserType , SalaryType]))
'Bob 100 Employee Hourly'
Upvotes: 4
Reputation: 14369
Python has two simple ways of constructing strings:
string formatting as explained here: https://docs.python.org/2/library/string.html
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
and the old style % operator https://docs.python.org/2.7/library/stdtypes.html#string-formatting
>>> print '%(language)s has %(number)03d quote types.' % \
... {"language": "Python", "number": 2}
Python has 002 quote types.
Upvotes: 2
Reputation: 20351
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'
Upvotes: 26
Reputation: 51
You have two options here:
.join()
method: " ".join(["This", "is", "a", "test"])
"%s, %s!" % ("Hello", "world")
Upvotes: 5