1,105,391 Community Members

substring in python

Member Avatar
biscayne
Light Poster
36 posts since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I have a table with product codes, the first two chars of the product code is the product group.
using the product group I'd like to test the content of certain data.

Would this be proper coding or is there a better way ?

if prodcust_code[:2] == "AB" do:
   ABsubroutine
if prodcust_code[:2] == "CC" do:
   CCsubroutine
if prodcust_code[:2] == "EF" do:
   EFsubroutine
if prodcust_code[:2] == "US" do:
   USsubroutine
Member Avatar
snippsat
Veteran Poster
1,041 posts since Aug 2008
Reputation Points: 483 [?]
Q&As Helped to Solve: 382 [?]
Skill Endorsements: 10 [?]
 
1
 

Something like this look better,and 'do' is not used in Python.

s = 'ABsomething'
if s.startswith(('AB','CC','EF','US')):
    print '{}subroutine'.format(s[:2])
else:
    print 'Substring not found'
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
1
 

If you want to call the appropriate function, do this ...

code = prodcust_code[:2]
if code == "AB":
   function_AB()
elif code == "CC":
   function_CC()
elif code == "EF":
   function_EF()
elif code == "US":
   function_US()
else:
    print("No function found for {}".format(code))
Question Answered as of 1 Year Ago by vegaseat and snippsat
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: