加载中...

Python

  1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Data Types

By Al Lukaszewski, About.com

7 of 10

Working With Variables

Working with Integer Variables

As you might imagine, you can perform any mathematical operation you like on a numeric literal.

d = 300
pi = 3.14159265
circumference = pi * d
r = d/2
c = 2 * pi * r
For more operators, see the page "Python Operators".

Working with Strings

With a string, one concatenates instead of adding. One can concatenate strings or their values. The result is a string that shows no indication that the two parts were ever separate. So if you need a space between the parts, you must be sure to include it when the two strings are joined.

a = 'big'
b = 'baboons'
phrase = a + b
full_phrase = b + " with " + a + " bahoochies"
print phrase
print full_phrase
output:
bigbaboons
baboons with big bahoochies

If you want more than one letter but still less than the whole string, you can cull out a substring by using the slicing operator:

>>> b = 'baboons'
>>> z = b[2:7]
>>> print z
boons

You can, of course, combine that substring with another string value and assign both to a single string literal.

>>> b = 'baboons'
>>> word = 'ball' + b[3:7]
>>> print word
balloons

7 of 10

Explore Python

More from About.com

Python

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.