Home > front end >  Is there a way to get strings and integers within a variable seperately in python?
Is there a way to get strings and integers within a variable seperately in python?

Time:04-20

If i take a input like below

input = "100 hours"

how can i take integers and strings seperately from the variable and assign them to two seperate variables

CodePudding user response:

You can use a regex with two groups to do that. A group is a part of a regex pattern enclosed in parentheses () metacharacter

For example:

import re

target_string = "100 hours"

# two groups enclosed in separate ( and ) bracket
result = re.search(r"([0-9] ).*([a-zA-Z] )", target_string)

# Extract matching values of all groups
print(result.groups())

# Output ('100', 'hours')

CodePudding user response:

You could use split along with tuple syntax here:

input = "100 hours"
(num, units) = input.split()
print(num)    # 100
print(units)  # hours

CodePudding user response:

You can try the following solution using regex:

import re 

input_string = "100 hours"
# substitute all the characters and spaces with an empty string
only_numbers = re.sub(r"[a-zA-Z ]", "", input_string) 
# substitute all the numbers with an empty string
only_characters = re.sub(r"[0-9]", "", input_string) 

print(only_numbers) # prints "100"
print(only_characters) # prints " hours"

The nice thing about this solution is that it will work no matter how the numbers and characters are distributed throughout the input string. You can tweak the regex in each statement to match your specific needs.

  • Related