String handling

Cards (19)

  • A string is a collection of characters e.g. “22A High Street”.
  • In Python a string is treated as a 1D array of characters and this makes string handling operations easier.  This means we can refer to the characters in a string separately by using an index number, starting [0] 
  • The len() function is used to find out the length of a string.  
  • Strings need to be enclosed in double or single quotes.
  • String slicing allows us to extract parts of a string. The syntax is str[start : end]. If no value is given for start it defaults to zero (the beginning). If no value is given for end then it defaults to the length of the string.
  • To concatenate two strings together, we can join them using the + operator or a comma.
  • The ord() function can be used to find the ASCII code of a character.
  • The chr() function converts an ASCII code into its character value.
  • The int() function can be used to convert a string to a numeric value.
  • The float() function can be used to convert a string to a floating point number.
  • The str() function can be used to convert an integer, float or datetime into a string.
  • The index() method is used to return the position of the first occurrence of a substring within a string.
  • The count() method counts the number of times that a given substring appears in a string.
  • The replace(old, new) method replaces all occurrences of old with new in a string.
  • The strip() method removes any leading/trailing whitespace from a string.
  • The split() method splits a string into a list based on a specified separator.
  • The join(iterable) method joins the elements of an iterable together into a single string.
  • The upper() method returns a copy of the string converted to uppercase.
  • The lower() method returns a copy of the string converted to lowercase.