Home Python Page 3 - String Manipulation

# Numbers and spaces - Python

Programmers need to know how to manipulate strings for a variety of purposes, regardless of the programming language they are working in. This article will explain the various methods used to manipulate strings in Python.

Rating:  / 96
May 02, 2005

SEARCH DEV SHED

TOOLS YOU CAN USE

We can check whether a string is alphanumeric:

>>> 'aa44'.isalnum()
True
>>> 'a\$44'.isalnum()
False

It is also possible to check whether a string contains only letters:

>>> 'letters'.isalpha()
True
>>> 'letters4'.isalpha()
False

Here's how you check whether a string contains only numbers:

>>> '306090'.isdigit()
True
>>> '30-60-90 Triangle'.isdigit()
False

We can also check whether a string only contains spaces:

>>> '   '.isspace()
True
>>> ''.isspace()
False

Speaking of spaces, we can add spaces on either side of a string. Let's add spaces to the right of a string:

>>> 'A string.'.ljust ( 15 )
'A string.      '

To add spaces to the left of a string, the rjust method is used:

>>> 'A string.'.rjust ( 15 )
'      A string.'

The center method is used to center a string in spaces:

>>> 'A string.'.center ( 15 )
'   A string.   '

We can strip spaces on either side of a string:

>>> 'String.'.rjust ( 15 ).strip()
'String.'
>>> 'String.'.ljust ( 15 ).rstrip()
'String.'

 >>> More Python Articles          >>> More By Peyton McCullough