Home arrow Python arrow Page 2 - String Manipulation

Splitting strings, making cases - 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.

TABLE OF CONTENTS:
  1. String Manipulation
  2. Splitting strings, making cases
  3. Numbers and spaces
  4. Regular Expressions
By: Peyton McCullough
Rating: starstarstarstarstar / 96
May 02, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Splitting a string is something I find myself doing often. The split method is used for this:

>>> test.split()
['This', 'is', 'just', 'a', 'short', 'string.']

We can choose the point that we split it at:

>>> test.split ( 'a' )
['This is just ', ' short string.']

Rejoining our split string can be done using the join method:

>>> ' some '.join ( test.split ( 'a' ) )
'This is just  some  short string.'

We can play around with the case of letters in our string, too. Let's make it all upper case:

>>> test.upper()
'THIS IS JUST A SHORT STRING.'

Now let's make it lowercase:

>>> test.lower()
'this is just a short string.'

Let's capitalize only the first letter of the lowercase string:

>>> test.lower().capitalize()
'This is just a short string.'

We can also use the title method. This capitalizes the first letter in each word:

>>> test.title()
'This Is Just A Short String.'

Trading case is possible:

>>> test.swapcase()
'tHIS IS JUST A SHORT STRING.'

We can run a number of tests on strings using a few methods. Let's check to see whether a given string is all upper case:

>>> 'UPPER'.isupper()
True
>>> 'UpPEr'.isupper()
False

Likewise, we can check to see whether a string contains only lower case characters:

>>> 'lower'.islower()
True
>>> 'Lower'.islower()
False

Checking whether a string looks like a title is simple, too:

>>> 'This Is A Title'.istitle()
True
>>> 'This is A title'.istitle()
False



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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: