We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,301 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

substring in python

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
3
Contributors
2
Replies
5 Hours
Discussion Span
3 Months Ago
Last Updated
3
Views
Question
Answered
biscayne
Light Poster
36 posts since Nov 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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'
snippsat
Posting Shark
957 posts since Aug 2008
Reputation Points: 482
Solved Threads: 344
Skill Endorsements: 8

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))
vegaseat
DaniWeb's Hypocrite
Moderator
6,476 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,611
Skill Endorsements: 36
Question Answered as of 3 Months Ago by vegaseat and snippsat

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0814 seconds using 2.69MB