Python Code Example: Converting Array to List in Python

To convert a call in Python to C, you can construct a corresponding structure. However, it is often simpler and clearer to use Python objects instead of explicit functions, especially when you intend to keep the code readable. Sharing data between C types and Python types can pose a challenge in such situations.


Solution 1:

The contents of

argv

consist of strings and are not analyzed as literals within the program.

Simply provide a string separated by commas, but exclude the enclosing brackets.

python3 test.py 1,2,3,4,5 0

Transform the input into an array by applying

split()

to it.

import sys
arr = sys.argv[1].split(',')
print(arr[2])


Solution 2:


Strings are the only acceptable format for commandline arguments. In order to utilize integers, they must be converted to

int

. If you choose to use the list syntax as demonstrated in the example, a parser must be used (either your own, one from

ast

, or

eval

— but not

eval

). However, there is a simpler solution: write each argument separately and use a slice of

sys.argv

as your list. Passing multiple arguments to a commandline program (such as multiple filenames for

less

,

rm

, etc.) is typically done using space separation.

python3 test.py -n a b c 1 2 3

Initially, you would single out and exclude the arguments that serve a distinct function (as depicted in the aforementioned example with

-n

), and subsequently retain the remaining ones.

arr = sys.argv[2:]
print(arr[3])   # Prints "1"

It is important to ensure that any argument from the shell is protected by using quotes to avoid any characters with special meaning (such as

*

and

;

), as well as spaces that are included as part of an argument. However, this issue should be addressed separately.

Frequently Asked Questions