Home > OS >  how to input a list and a string seperated by comma in one line in python
how to input a list and a string seperated by comma in one line in python

Time:12-06

[4, 3, 2, 6] , N = 4

this is my input and I want to get the list and 4 and store all in a and b (a for the list and b for the integer)

a = list(map(int, input().strip(' []').split(',')))

i know how to get the list but I dont know how to get n because of the comma "," after and "N =" .

CodePudding user response:

Use a regex, remove all non-digit/non-comma, then split on comma

value = "[4, 3, 2, 6] , N = 4"
*a, b = list(map(int, re.sub(r'[^\d,]', '', value).split(',')))

print(a)  # [4, 3, 2, 6]
print(b)  # 4

Here are the steps

re.sub(r'[^\d,]', '', value)                             # '4,3,2,6,4'
re.sub(r'[^\d,]', '', value).split(',')                  # ['4', '3', '2', '6', '4']
list(map(int, re.sub(r'[^\d,]', '', value).split(',')))  # [4, 3, 2, 6, 4]

Then using packing you can save all the first ones in a variable, and the last one in another

CodePudding user response:

Assuming the input format is exactly as shown in the question then:

import re

text = '[4, 3, 2, 6] , N = 4'

*a, b = map(int, re.findall(r'(\d )', text))

print(a)
print(b)

Output:

[4, 3, 2, 6]
4

CodePudding user response:

Using join() method Algorithm (Steps) Following are the Algorithm/steps to be followed to perform the desired task −

Create a list and add some dummy strings to it.

Get the comma-separated string from the list by passing the list as an argument to the join() function(join() is a string function in Python that is used to join elements of a sequence that are separated by a string separator. This function connects sequence elements to form a string) and create a variable to store it.

Here we pass delimiter as ‘,’ to separate the strings with comma(‘,)

Print the result of a comma-separated string.

CodePudding user response:

One option:

import re
from ast import literal_eval

inpt = input('list, then assignment: ')

lst, var = re.split(r'(?<=])\s*,\s*', inpt)

lst = literal_eval(lst)
# [4, 3, 2, 6]

key, val = re.split(r'\s*=\s*', var)
var = {key: literal_eval(val)}
# {'N': '4'}

print(lst, var)

Output:

list, then assignment: [4, 3, 2, 6] , N = 4
[4, 3, 2, 6] {'N': 4}

Other example:

list, then assignment: ['a', 'b', None] , Y = 'abc'
['a', 'b', None] {'Y': 'abc'}
  • Related