Home arrow Python arrow Page 3 - Python Strings: Spinning Yarns

Changing Strings with Methods - Python

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.

TABLE OF CONTENTS:
  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
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

We can use various methods to change the data in a string. We touched on slicing and concatenation earlier in the article, and I am going to talk about it just a little more here. Before, we replaced an entire word; this time we will only replace part of a word:

speech='A toast, to bread, whom without there would be no taste'

what='No wait that is not right'

print speech

print what

speech=speech[0:51] + 'oa' + speech[52:54]

print speech

Which would produce the following output:

  A toast, to bread, whom without there would be no taste

  No wait that is not right

  A toast, to bread, whom without there would be no toast

We could also use the replace method, which might prove to be a little easier:


speech='A toast, to bread, whom without there would be no taste'

what='No wait that is not right'

print speech

print what

speech=speech.replace('taste','toast')

print speech

Resulting in:

  A toast, to bread, whom without there would be no taste

  No wait that is not right

  A toast, to bread, whom without there would be no toast

This would also be handy if, say, a certain writer by the name of James Payne began dating your mother:


oldFather='Your father is named...whatshisname...'

print oldFather

oldFather=oldFather.replace('whatshisname', 'James Payne the new Hawtness')

print oldFather

And the shocking results:

  Your father is named...whatshisname...

  Your father is named...James Payne the new Hawtness...



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

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: