Dan O'Boyle
Dan O'Boyle

Reputation: 3766

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)

Upvotes: 17

Views: 64999

Answers (5)

dumbledad
dumbledad

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

Kasravnd
Kasravnd

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

Klaus D.
Klaus D.

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

anon582847382
anon582847382

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

Thomas
Thomas

Reputation: 51

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")

Upvotes: 5

Related Questions