Addohm Addohm - 2 years ago 201
Python Question

Python VBA-like left()

I've been looking around but don't see anything similar to what I'm looking for. Within a django site I want to add some code that looks at a values furthest left (or the first) character in a variable (which is populated by a DB query), and if it's a particular letter or number, do something with said variable. How can I do this?

Answer Source

This checks if the first letter in mystring is 'a' or 'b'.

if mystring[0] in ('a', 'b'):
    # whatever

Use slicing to test for longer substrings:

if mystring[:2] in ('abc', 'def', '987'):
    # whatever

Alternatively you can use str.startswith():

if mystring.startswith(('SUBTOTAL', 'TOTAL')):
    # whatever
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download