Does Python have a function to neatly build a string that looks like this:
Bob 100 Employee HourlyWithout building a string like this:
EmployeeName + ' ' + EmployeeNumber + ' ' + UserType + ' ' + SalaryTypeThe 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) 5 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' 1 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")
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' Python has two simple ways of constructing strings:
string formatting as explained here:
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'and the old style % operator
>>> print '%(language)s has %(number)03d quote types.' % \
... {"language": "Python", "number": 2}
Python has 002 quote types.