Home > Enterprise >  Take a List and an integer as input from user
Take a List and an integer as input from user

Time:01-05

I want to take list and an integer as input from user. I tried using split method in following way:

lst,n=input().split(",")
print(lst)
print(n)

Input:

[1,2,3,4],5

Output expected:

[1,2,3,4]
5

CodePudding user response:

You could match either from [...] or match 1 or more digits using a pattern with an alternation

import re

pattern = r"\[[^][]*\]|\d "
s = "[1,2,3,4],5"
print(re.findall(pattern, s))

Output

['[1,2,3,4]', '5']

Or a bit more precise only matching digits optionally separated by a comma, spaces and more digits:

\[\s*\d (?:\s*,\s*\d )*\s*]|\d 

CodePudding user response:

It would be easier if you just omitted the brackets and used extended iterable unpacking.

*lst, n = map(int, input().split(','))

This will give you lst = [1, 2, 3, 4], and n = 5 for the input 1,2,3,4,5.

Note/caveat: an input of 1 will give you lst = [] and n = 1.

CodePudding user response:

To be able to write lst,n = ..., you need the input to be split only once, on the last comma. So, instead of str.split, you should use str.rsplit(maxsplit=1).

Then, since the list is surrounded by [ and ] characters, you need to discard those before splitting the list.

Finally, since the input is made of characters but you want numbers, you should call int to convert the strings to numbers.

def list_and_number(s):
    s,n = s.rsplit(',', maxsplit=1)
    n = int(n)
    lst = [int(x) for x in s.strip('[]').split(',')]
    return lst, n

lst, n = list_and_number(input())
print(lst)
print(n)

# INPUT
[1,2,3,4],5

# OUTPUT
[1, 2, 3, 4]
5

CodePudding user response:

If you want to give an external input to a program you can just define it as sys.argv

import sys

print("Give me the list")
lst = sys.argv[0]
print("Give me the number")
num = sys.argv[1]
  •  Tags:  
  • Related