Home arrow Python arrow Page 4 - Python: More Fun with Strings

Putting Our Strings to the Test - Python

In our last article we left off discussing ways to manipulate strings in Python, like concatenating, repeating, escape characters, and so forth. In this episode we will pick up where we left off and learn some more ways to work with strings, starting with the comparison method.

TABLE OF CONTENTS:
  1. Python: More Fun with Strings
  2. Working with String Methods
  3. Capital Idea(s)
  4. Putting Our Strings to the Test
  5. Converting Data and Sorting
By: James Payne
Rating: starstarstarstarstar / 5
February 04, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Sometimes it is necessary to test the data in a string. Maybe we want to know if it contains a specific letter or word or sentence, or any text at all. We can perform a true/false boolean test like so:


>>> cartoon='The Smurfs rock.'

>>> 'snork' in cartoon

False

>>> 'smurf' in cartoon

False

>>> 'smurfs' in cartoon

False

>>> 'Smurfs' in cartoon

True

>>> 'Smurf' in cartoon

True

>>> 'rock' in cartoon

True

>>> 'The Smurfs' in cartoon

True

>>> 'The Smurfs suck' in cartoon

False

>>> 'The Smurfs rock' in cartoon

True

In the above example we assign the value "The Smurfs rock." to the variable cartoon. We then run a number of tests to see if certain words and eventually sentences appear in the cartoon variable. You will note that the method is case sensitive (it won't find 'smurfs' but it will find 'Smurfs').

You can also use "not in," to see if text is not in the string, like this:


>>> 'Snorks' not in cartoon

True

Another method of testing whether some text is in a string is to use the find() method, which returns the position of the text in the string:


>>> cartoon.find('Smurfs')

4

>>> cartoon.find('rock')

11

>>> cartoon.find('boo')

-1

As you can see, the word 'Smurfs' begins at the fourth character, and 'rock' begins at the eleventh character (spaces count as one character). Since the text 'boo' is not in our string, the program returns the value -1.



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