No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python argparse Comma Separated List

by Khaleel O.
January 1, 2022
in Python
Reading Time: 5 mins read
A A
python argparse comma separated list
python argparse comma separated list

Hi! Let’s learn how to use python argparse with a comma separated list of values. We will be using Python 3.8.10. Let’s go! ⚡⚡✨✨

If you haven’t already done so, please visit our previous tutorial on python argparse HERE. It should help you understand how argparse works before jumping into this awesome tutorial.

Ok! In this example, we will use argparse to accept and calculate the sum of a comma separated list of prices. Let’s write our code:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--prices",type=str,required=True)

d = vars(parser.parse_args())

if "prices" in d.keys():
    d["prices"] = [float(s.strip()) for s in d["prices"].split(",")]

sum = 0

for p in d["prices"]:
    sum += p

print(f"The total is: {sum:.2f}")

Let’s explain what is happening here:

  1. We import the argparse library first, as usual.
  2. Method argparse.ArgumentParser() creates a new ArgumentParser object. The new object is called parser.
  3. add_argument() defines how a single command line argument should be parsed. The name of the argument is –prices, the type is str and the required flag is True. Note that the name of the argument must include 2 hyphens and not one.
  4. parse_args() converts argument strings to objects. In this case, we nest this call in the method vars. Recall that the method vars returns the __dict__ attribute of the supplied object. In this case it returns the __dict__ attribute of the parser object parser as d. Object d will be a dictionary object that contains a key value pair with the key value prices (our argument) and the comma separated values supplied for argument prices.
  5. We check to see if indeed our dictionary object d contains the key value prices. If so, we split up the values of the comma separated list into separate numbers using the comma as a delimiter and strip extra whitespace from each value. After this step is complete, we will have a clean dictionary that contains each value of the comma separated list as a separate value of type float.
  6. We declare a new variable sum which will contain the sum of the comma separated values.
  7. We calculate the sum of all the values in our dictionary.
  8. Print the value to the screen formatted to two decimal places.

Because we used argparse, we must type the correct command at the command line in order for our script to do its job. See the below screenshot as a guide:

python argparse comma separated list
python argparse comma separated list

Let’s explain what is happening here:

  1. Ideally, you’d first open a new cmd window on Windows 10 or a new Terminal on Linux/Mac and type something very similar to the above command.
  2. The python executable name is usually python but this may differ depending on how you configured your system and python interpreter.
  3. The python script name is the name of the script file. On my system, the filename is PYTHON_ARGPARSE_COMMA.py. Ensure that your current directory contains this file and that you spell it correctly.
  4. The argument name as defined in our code is prices, with 2 hyphens. This is what we must type at the command line. If you misspell this or leave this out, you will get an error.
  5. The value of the parameter is a comma separated list of values with no spaces. This is the actual value of the parameter. If you omit this, you will get an error. If you do not use a comma to separate the values, you will also get an error. You may use as many or as few comma separated values as you wish, but it must have at least one value.
  6. Make sure that you put one space between each part of the above command when you practice this on your own machine.

If all goes well, when you execute this script you will get something similar to the following output (different totals depending on your list of comma separated values):

#output
#The total is: 111.71

Awesome! So we were able to use python argparse to create a comma separated list of values. You can find the full argparse documentation HERE.

Thanks for reading and good luck!


Are you worried about your child’s online safety or your employees’ productivity? Do you wonder what they’re accessing on their devices? SentryPC is here to address these concerns. This all-in-one, cloud-based software provides robust activity monitoring, content filtering, and time management, making it ideal for both parental control and employee monitoring. Embrace peace of mind and enhanced efficiency with SentryPC, the proactive solution to your digital monitoring needs. CLICK HERE to get started.

Tags: argparse
Previous Post

Python argparse Example with Code

Next Post

Python async await Simple Example

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy