Sometimes, while working with Python strings of data, we can have a problem in which we need to separate positive and negative integers in a string. This can occur in many domains that include data handling. Let us discuss the certain ways in which we can solve this problem.
Method 1: Using regex
This problem can be solved using appropriate regex. In this, we match the matching regex with the string and separate the positive integers and negative integers from the string.
step-by-step approach
- Initialize a string test_str with some content.
- Print the original string.
- Use the re.findall() function to extract all contiguous sequences of digits (positive or negative) from the string.
- The regular expression ‘[-+]?\d+’ is used to match sequences of digits, optionally preceded by a plus or minus sign.
- The findall() function returns a list of all matches found in the string.
- Print the resulting list of integers.
Python3
# Python3 code to demonstrate working of # Segregate Positive and Negative Integers # Using regex import re # initializing string test_str = "gfg + 4-1is + 5best-8" # printing original string print ( "The original string is : " + test_str) # Segregate Positive and Negative Integers # Using regex res = re.findall( '[-+]?\d+' , test_str) # printing result print ( "The split string is : " + str (res)) |
The original string is : gfg+4-1is+5best-8 The split string is : ['+4', '-1', '+5', '-8']
The time complexity of the given code is O(n), where n is the length of the input string.
The space complexity of the code is O(m), where m is the number of positive and negative integers in the input string.
Method 2: Using loops
Approach:
- Initialize two empty lists pos_list and neg_list.
- Loop through each character in the string test_str.
- If the character is a digit, convert the string of digits until the next non-digit character to an integer using int() function.
- If the character immediately preceding the integer is ‘+’, append the integer to the pos_list, otherwise append it to the neg_list.
- Join the two lists and print the result.
Python3
test_str = "gfg + 4-1is + 5best-8" print ( "The original string is : " + test_str) pos_list = [] neg_list = [] i = 0 while i < len (test_str): if test_str[i].isdigit(): j = i while j < len (test_str) and test_str[j].isdigit(): j + = 1 num = int (test_str[i:j]) if i > 0 and test_str[i - 1 ] = = '+' : pos_list.append(num) else : neg_list.append(num) i = j else : i + = 1 result = pos_list + neg_list print ( "The split string is : " + str (result)) |
The original string is : gfg + 4-1is + 5best-8 The split string is : [4, 1, 5, 8]
Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(m), where m is the number of integers in the string.