0

I have seen the below link for my answer but still didn't get an expected answer.

If I provide Name and Number in one line, Python should take the first value as a string and second as an integer.

3

4 Answers 4

6
a, b = [int(x) if x.isnumeric() else x for x in input().split()]

It will convert to int any part of input if possible.

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

Comments

0
s, num = input("Give str and int :\n").split()
num = int(num)
print(s, type(s))
print(num, type(num))

Output :

Give str and int :
hello 23
hello <class 'str'>
23 <class 'int'>

4 Comments

It is not one liner.
Thanks @phoenixo, but is there any possibility without typecasting the string into integer value?
@MahendrasingJPardeshi You have to use typecasting because everything what you put in input is a string.
Sorry, I thought the input had to be "in one line", not the code
0

If you're certain to have a string and a number you can use list comprehension to get the values of both.

x = "Hello 345"

str_value = "".join([s for s in x if s.isalpha()])  # list of alpha characters and join into one string
num_value = int("".join([n for n in x if n.isdigit()]))  # list of numbers converted into an int

print(str_value)
>> Hello

print(num_value)
>> 345

Comments

0

You can get the string and int by using regular expressions as follows:

import re

input_text = "string489234"

re_match = re.match("([^0-9]*) ?([0-9]*)", input_text)

if re_match:
    input_str = re_match.group(1)
    input_int = re_match.group(2)

see: https://docs.python.org/3/library/re.html

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.