Wednesday, 18 July 2007

Python strings (vs. Java strings)

Python strings are more or less similar to Java strings. A difference is the formatting of Python strings are done in the strings themselves. Also Python strings have more methods than their Java counterparts.

The Python methods, find (the same as index) and rfind (rindex) have their Java opposite, indexOf and lastIndexOf. So does lower and upper in the Java methods toLowerCase and toUpperCase. split, replace, startsWith and endsWith are common to Python and Java.

join, the opposite of split, does not have a Java equivalent. The join method concatenates the members of a string sequence together with a specified divider. Neither do these methods: count, isalpha, isalnum, isdigit, islower, capitalize, isupper, title, istitle, swapcase, expandtabs and translate.

The string formatting operator, the percent (%) sign, does all the work as an example from the Beginning Python: From Novice to Professional book shows:
>>> format = "Hello, %s. %s enough for ya?"
>>> values = ('world', 'Hot')
>>> print format % values
Hello, world. Hot enough for ya?
Templates strings are another way of formatting. Basically these are strings with variables that are substituted with the actual value. Below are two examples from the book:
>>> from string import Template
>>> s = Template('$x, glorious $x!')
>>> s.substitute(x='slurm')
'slurm, glorious slurm!'
>>> s = Template("It's ${x}tastic!")
>>> s.substitute(x='slurm')
"It's slurmtastic!"
A third example uses a dictionary for substitution with value-name pairs:
>>> s = Template('A $thing must never $action.')
>>> d = {}
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'

No comments: