Home arrow Python arrow Python Strings: Spinning Yarns

Python Strings: Spinning Yarns

As the students used to say to Mr. Kotter: "Welcome back, welcome back, welcome back." In our previous article we talked some more about how to manipulate strings in Python, leaving off with indexing and slicing. Here, we will pick up again with slicing, using it to “change” the contents of a string.

  1. Python Strings: Spinning Yarns
  2. The Interpolation Operator
  3. Changing Strings with Methods
  4. Dealing with Multiple Words
By: James Payne
Rating: starstarstarstarstar / 3
February 11, 2008

print this article


I say "change" in quotation marks because technically strings are immutable, or in less fancy speak, they are like a hippy's views of the world -- they cannot be changed. Unless of course the 1980s and big business rolls around and those hippies discover the wonderful world of free commerce. You get a job you damn hippy!

Just a side note: hippy is not in my Word dictionary, but Lippy, Tippy, Pippy, and Hippo are for some reason.

Tricking the Computer

I don't know why we have to trick the computer in order to change a string. I mean, why couldn't strings just be changeable? Because computer programmers like to mess with you, that's why, especially the ones that create languages and specifically the ones that create open source languages. They don't make money, so their sole satisfaction is to confound you. And let's face it, that isn't too hard to do.

Here is how we "change" those hippy strings. Note that we will be writing this code at the command prompt of our Python shell.

>>> woodstock='I am a hippy'

>>> wallstreet=woodstock[0:7] + 'yuppie'

>>> print wallstreet

I am a yuppie

Let's have a little more fun with it. In the following example, we will assign the alphabet to a variable named, well, alphabet, then use slicing to print out the coolest name in history. Note that the index number for the string begins with 0, so for instance, a is index 0, b is in index 1, and z is index 25, as opposed to 26.

>>> alphabet='abcdefghijklmnopqrstuvwxyz'

>>> name=alphabet[9]+alphabet[0]+alphabet[12]+alphabet[4]+alphabet[18]

>>> print name


>>> More Python Articles          >>> More By James Payne

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: