0

[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 =" .

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I posted only to find that my answer was very similar to yours :) . I liked yours better. Hence I deleted mine, and upvoted yours. Great work !!
0

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.

Comments

0

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'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.