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 …

print("Hello\nWorld");

and is taken literally when contained within single quotes …

print('Hello\nWorld');

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

print('Hello\nWorld')
print("Hello\nWorld")

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

print(r"Hello\nWorld")
print(r'Hello\nWorld')

using single or double quotes.

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

print('''\
Hello
World''')

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)
print(newString)

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 …

.upper()

.lower()

.capitalize()

.strip()

.rstrip()

.find(substring)

.replace(‘this’, ‘that’)

.isalnum()

.isalpha()

.isdigit()

.isprintable()

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