Nov 21, 2024

Wiki

Python

Aide

edit SideBar

Search

The strings


General information

Presentation

Character strings are a type of composite data consisting exclusively of characters. They cannot be modified: you must create a new channel, and copy what you want to change.

Definition, and display

They are defined with apostrophes, or quotation marks: 'aze' and "sqd" are two strings.

  >>> chain = "Hello"
  >>> chain
  Hello
  >>> type(string)
  <type'str'>

We read a string with 'raw_input()', possibly passing the message to be displayed as an argument. The result is displayed with 'print()':

  >>> chaine = raw_input()
  Coucou
  >>> print chaine
  Coucou
  >>> dd = 'CouCou'
  >>> 'ou' in dd
  True
  >>> chaine2 = raw_input("Your string: ")
  Your string: Coucou2
  >>> print chaine2
  Coucou2

We can quite easily place a \n in a string, in which case we will have the expected line break.

Basic operations

If toto is a string, toto[i] is the character i+1 of this string, and len(toto) its length. Finally, we can concatenate two strings with +, and also use * :

  >>> toto = "abcde"
  >>> len(toto) 
  5
  >>> toto[0]
  a
  >>> toto[1]
  b
  >>> toto[-1]
  e
  >>> toto + "fg" + "fg
  abcdefg
  >>> "fg"*3
  fgfgfgfg

We convert the string s='123' into a number by int(s) (float, if it is a real one). Finally, the number N=123 is transformed into strings by str(N)...

  >>> s = '123'
  >>> s, type(s)
  ('123', <type'str' >)
  >>> n = int(s)
  >>> n, type(n)
  (123, <type'int'>)
  >>> str(n), n
  ('123', 123)

For, if and strings

Use of the for.

The for loop can go through a string of characters. For example:

  >>> for k in "letters":
  .... print k
  ... 
  l
  e
  t
  t
  r 
  e
  s

Each letter of the letters word is displayed, one per line.

Use of the if

In the same spirit, the condition of the if can relate to the membership of a character in a string:

  >>> toto = 'aze'
  >>> if 'a' in toto:
  ...     print toto
  ...
  aze

In the above, the condition is verified, so 'aze' is displayed. We can use "not in" instead of "in" if necessary.

Methods of the class str

Modifications of a string

The methods

replace(str1,str2)
Replace str1 by str2 in the current string.
capitalize()
Makes the first character of the current string capitalized, and the rest lowercase.
lower()
Sets the characters of the current string to lowercase.
upper()
Sets the characters of the current string to upper case.
swapcase()
Upper-case to lower-case and vice versa.
ljust(int)
Complete the string with spaces, until it has the length int (does nothing if the string is already larger.)
lstrip(str)
If str is at the top of the current string, delete it.

In the two previous methods, one can replace "l" by "r", to perform the actions not on the left, but on the right.

Example of modifications

Let's illustrate some of the previous methods:

  >>> "abs".replace('s','c')
  "abc
  >>> "qAd".lstrip('A')
  "qAd
  >>> "qAd".lstrip('qA')
  'd'

Tests on a chain

The methods

endswith(str)
Tests whether the string concerned ends with the str string.
startswith(str)
Tests whether the string concerned begins with the str string.
isdigit()
Tests whether the string concerned consists of numbers.
isalpha()
Tests whether the string concerned consists of letters.
isalnum()
Tests whether the string concerned consists of alphanumeric characters.
islower()
Tests whether the string concerned contains only lower-case letters.
isupper()
Tests whether the string concerned contains only upper case letters.
isspace()
Tests if the concerned string contains only spaces.

Examples of tests

Let's illustrate the previous methods:

  >>> "toto".endswith('o')
  True
  >>> "azea".islower()
  True

Miscellaneous

The methods

Other methods that can be applied to an object of the str class:

count(str)
Count the number of occurrences of str.
encode('utf8')
Encodes the string in utf8 (or'ascii','latin1','iso-8859-15').
join(str)
Inserts the current string between each str character.
find(str)
Returns the location of the first occurrence of str in the current string, and -1 if str has not been found.
split(str)
Cuts the current string as soon as it meets the str string.
splitlines()
Corresponds to split('\n').
zfill(int)
If the current string is smaller than int, 0s are placed at the beginning of the string until the desired length is reached.

Examples of this

Let's illustrate the previous methods:

  >>> "aze'.join('xwc')
  "xazewazec
  >>> "abs'.find('s')
  2
  >>>> "q d ez zzz".split(' ')
  ['q','d','ez','zzz']

Practical work

From lowercase to uppercase

  1. Make a piece of code to capitalize all the letters of a word.
  2. Make a piece of code to capitalize all the words in a sentence.
  3. Finally, make a piece of code to transform each word in a sentence into: a capital letter, followed by lower-case letters. For example, "Hello how are you?" will become "Hello How Are You?"

Secret codes

Encrypt/decrypt a string of characters, using the so-called sawtooth transposition method: to encrypt the message

sawtooth transposition

we write it on two lines, just like a sawtooth:

                      t a s o i i n n a n d d s i d
                       r n p s t o e d n s e c e

This gives, when we concatenate the two lines, the figure:

tasoiinnetdsirnpstoednsece

Two functions can be performed: one for encryption and the other for decryption.

Page Actions

Recent Changes

Group & Page

Back Links