Home arrow Python arrow String Manipulation

String Manipulation

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.

  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



String manipulation is very useful and very widely used in every language. Often, programmers are required to break down strings and examine them closely. For example, in my articles on IRC (http://www.devshed.com/c/a/Python/Python-and-IRC/ and http://www.devshed.com/c/a/Python/Basic-IRC-Tasks/), I used the split method to break down commands to make working with them easier. In my article on sockets (http://www.devshed.com/c/a/Python/Sockets-in-Python/), I used regular expressions to look through a website and extract a currency exchange rate.

This article will take a look at the various methods of manipulating strings, covering things from basic methods to regular expressions in Python. String manipulation is a skill that every Python programmer should be familiar with.

String Methods

The most basic way to manipulate strings is through the methods that are build into them. We can perform a limited number of tasks to strings through these methods. Open up the Python interactive interpreter. Let's create a string and play around with it a bit.

>>> test = 'This is just a simple string.'

Let's take a fast detour and use the len function. It can be used to find the length of a string. I'm not sure why it's a function rather than a method, but that's a whole nother issue:

>>> len ( test )

All right, now let's get back to those methods I was talking about. Let's take our string and replace a word using the replace method:

>>> test = test.replace ( 'simple', 'short' )
>>> testa
'This is just a short string.'

Now let's count the number of times a given word, or, in this case, character, appears in a string:

>>> test.count ( 'r' )

We can find characters or words, too:

>>> test.find ( 'r' )
>>> test [ 18 ]

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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


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