Introduction to Python Strings

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Python Strings

In PHP, the \n gets interpolated when contained within double-quotes …


and is taken literally when contained within single quotes …


In Python, the \n takes effect and gives you a newline character regardless of whether it is contained within single or double quotes …


To print the literal \n, you need to do Python raw string


using single or double quotes.

In Python, you can use triple quotes (which is kind of like here-docs in PHP) …


This works with single or double quotes.  The \ escapes the  return character (think of it like a line-continuation character).

Here is an example of split and join strings …

myString = "This    is   some text"
words = myString.split()
newString = ', '.join(words)

The split() without argument will fold and split on whitespace.  Passing in another type of token will not fold, but will split on that token.  Note that join operates on the token and not on the words.

Besides split(), the string object has other methods like …







.replace(‘this’, ‘that’)





Note that string is immutable and the string is not changed.  But a new string is returned.

.format() works like this…

a, b = 10, 17
print('a is {} and b is {}'.format(a,b))

You can put in a positional index (starts from 0)  in the curly braces …

a, b = 10, 17
print('a is {0} and b is {1} and a is still {0}'.format(a,b))
# You can also do ...
print('a is {alpha} and b is {beta}'.format(alpha=a, beta=b))