Difference between revisions of "String"

m (String Operations)
m (typo fix)
Line 14: Line 14:
 
*<tt>len(s)</tt> returns the number of characters in the string s.
 
*<tt>len(s)</tt> returns the number of characters in the string s.
 
*<tt>s.lower()</tt> returns a copy of s, but with all uppercase characters converted to lowercase. (useful if you don't want a test to be case-sensitive)
 
*<tt>s.lower()</tt> returns a copy of s, but with all uppercase characters converted to lowercase. (useful if you don't want a test to be case-sensitive)
*<tt>s.split([sep])</tt> returns a [[list]] whose elements are the words in the string.  The parameter <tt>sep</tt> is optional, by default strings are split on all whitespace (spaces, tabs, newlines).  For example, <tt>'To be, or not to be.".split()</tt> will evaluate to <tt>['To', 'be,', 'or', 'not', 'to', 'be.']</tt>.  Note that split doesn't remove punctuation.
+
*<tt>s.split([sep])</tt> returns a [[list]] whose elements are the words in the string.  The parameter <tt>sep</tt> is optional, by default strings are split on all whitespace (spaces, tabs, newlines).  For example, <tt>'To be, or not to be.'.split()</tt> will evaluate to <tt>['To', 'be,', 'or', 'not', 'to', 'be.']</tt>.  Note that split doesn't remove punctuation.
  
 
==See Also==
 
==See Also==

Revision as of 12:21, 30 March 2011

A string is a primitive datatype in most programming languages that represents an ordered sequence of characters. In most languages strings are delimited with double quotes ("this is a string"), but in Python strings can be delimited by double or single quotes ('this is also a string in Python').

To a computer, strings are conceptually different from numbers, so for example the string "222" has nothing to do with the integer 222. To convert between strings and numbers in Python use type conversion functions.

String Operations

Some Python operations have special behaviors on strings. Notably,

  • + combines two strings in a process called concatenation. For example, 'Stan'+'ford' will evaluate to 'Stanford'.
  • * repeats a string a (positive integral) number of times. For example, 'spam'*3 will evaluate to 'spamspamspam'.
  • x in s will test if x is a substring of s.
  • s[i] will return the i'th character of string s. Note that like other Python sequence types string indices start at zero.
  • Strings can be sliced.

Useful Functions

  • len(s) returns the number of characters in the string s.
  • s.lower() returns a copy of s, but with all uppercase characters converted to lowercase. (useful if you don't want a test to be case-sensitive)
  • s.split([sep]) returns a list whose elements are the words in the string. The parameter sep is optional, by default strings are split on all whitespace (spaces, tabs, newlines). For example, 'To be, or not to be.'.split() will evaluate to ['To', 'be,', 'or', 'not', 'to', 'be.']. Note that split doesn't remove punctuation.

See Also