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.'
Please enable JavaScript to view the comments powered by Disqus. blog comments powered by