Strings

A string is a list of characters and, in Python, they are easy to declare using speech marks.

myquote = “Talk is cheap. Show me the code.”

Get the length of a String in Python

Getting the length of a string in python is the same as with a list

Getting a sub string in Python

You can access individual letters in Python using the index (as per a list) e.g

but also you can return a sub string e.g.

This SO answer has a good explanation of slices.

Spliting Strings.

You will often want to split a string into parts.  Maybe its a line from a file that you want to see as words or a date that you would like to split into day, month and year.

Converting text in a Python String

There are a number of different text conversions in Python that convert Strings into a new format e.g.

Testing a string for letters, numbers in Python

You can also test a string to see if it contains certain elments or is of a certain type:

Replacing Characters in a String

There are a number of ways to replace characters (or sub strings) in a string including regular expressions.  The simpliest way to start with is replace.  The following example will replace any a with a !

Other string operations to consider

  • You can trim strings in Python
  • You can join strings normally with a + or use the join method to include a delimiter (seperating character).

 

Last Updated:
Posted in Python

Comments 0

Write a Reply or Comment

We will not publish your email.*


*