Home arrow Python arrow Page 4 - Python 101 (part 2): If Wishes Were Pythons

Sliced And Diced - Python

Begin your tour of Python with a look at its number and stringtypes, together with examples of how they can be used in simple Pythonprograms. Along the way, you'll also learn how to build conditionalexpressions, slice and dice strings, and accept user input from the commandline

  1. Python 101 (part 2): If Wishes Were Pythons
  2. Tax Evasion
  3. Q
  4. Sliced And Diced
  5. Comparing Apples And Oranges
  6. If Only...
  7. Tying Up The Loose Ends
  8. Cookie-Cutter Code
  9. Time For Lunch
By: Vikram Vaswani, (c) Melonfire
Rating: starstarstarstarstar / 3
May 31, 2001

print this article


In Python-lingo, strings are an "immutable" object type, which means that they cannot be changed in place; the only way to alter a string is to create a new string with the changes. Python comes with powerful built-in operators designed to make it easier to extract subsections of a string, and thereby create new strings.

For example, to extract the letter "b" from the string "hobgoblin", I could use

>>> str = "hobgoblin" >>> str[2] 'b' >>>
This is referred to as "slicing"; the square braces [ and ] specify the starting and ending location (or "index") for the slice. Note that the first character is referred to by index 0.

You can extract a substring by specifying two indices within the square braces...

>>> str = "hobgoblin" >>> str[3:9] 'goblin' >>>
...and watch what happens when I omit either one of the two indices.

>>> str = "hobgoblin" >>> str[3:] 'goblin' >>> str[:7] 'hobgobl' >>>
You can also use negative indices, to force Python to begin counting from the right instead of the left.

>>> str = "hobgoblin" >>> str[-6] 'g' >>> str[-6:] 'goblin' >>>
The built-in len() function can be used to calculate the number of characters in a string,

>>> str = "hobgoblin" >>> len(str) 9 >>>
while the "in" and "not in" operators can be used to test for the presence of a particular character in a string. A match returns 1 (true), while a failure returns 0 (false).

>>> str = "hobgoblin" >>> "g" in str 1 >>> "x" in str 0

>>> More Python Articles          >>> More By Vikram Vaswani, (c) Melonfire

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: