Python | Segregate Positive and Negative Integers from mixed string

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. Lets discuss certain way in which we can solve this problem.

Method : Using regex
This problem can be solved using appropriate regex. In this, we match the matching regex with string and separate the positive integers and negative integers from the string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


Output :

The original string is : gfg+4-1is+5best-8
The split string is : ['+4', '-1', '+5', '-8']
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.