How do you separate alphanumeric in python?

I am trying to work out a simple function to capture typos, e.g:

"Westminister15"
"Westminister15London"
"23Westminister15London"

after fixating:

["Westminister", "15"]
["Westminister", "15", "London"]
["23", "Westminister", "15", "London"]

First attempt:

 def fixate(query):
     digit_pattern = re.compile(r'\D')
     alpha_pattern = re.compile(r'\d')
     digits = filter(None, digit_pattern.split(query))
     alphas = filter(None, alpha_pattern.split(query))
     print digits
     print alphas

result:

 fixate("Westminister15London")

 > ['15']
 > ['Westminister', 'London']

However, I think this could be done more effectively, and I still get bad results when I try something like:

 fixate("Westminister15London England")

 > ['15']
 > ['Westminister', 'London England']

Obviously it should enlist London and England separately, but I feel my function will get overly patched and theres a simpler approach

This question is somewhat equivalent to this php question

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given string str, divide the string into three parts one containing a numeric part, one containing alphabetic, and one containing special characters. 

    Examples: 

    Input : geeks01for02geeks03!!!
    Output :geeksforgeeks
            010203
            !!!
    Here str = "Geeks01for02Geeks03!!!", we scan every character and 
    append in res1, res2 and res3 string accordingly.
    
    Input : **Docoding123456789everyday##
    Output :Docodingeveryday
            123456789
            **##

    Steps : 

    1. Calculate the length of the string.
    2. Scan every character(ch) of a string one by one
      • if (ch is a digit) then append it in res1 string.
      • else if (ch is alphabet) append in string res2.
      • else append in string res3.
    3. Print all the strings, we will have one string containing a numeric part, other non-numeric part, and the last one contains special characters.

    Implementation:

    C++

    #include<bits/stdc++.h>

    using namespace std;

    void splitString(string str)

    {

        string alpha, num, special;

        for (int i=0; i<str.length(); i++)

        {

            if (isdigit(str[i]))

                num.push_back(str[i]);

            else if((str[i] >= 'A' && str[i] <= 'Z') ||

                    (str[i] >= 'a' && str[i] <= 'z'))

                alpha.push_back(str[i]);

            else

                special.push_back(str[i]);

        }

        cout << alpha << endl;

        cout << num << endl;

        cout << special << endl;

    }

    int main()

    {

        string str = "geeks01$$for02geeks03!@!!";

        splitString(str);

        return 0;

    }

    Java

    class Test

    {

        static void splitString(String str)

        {

            StringBuffer alpha = new StringBuffer(),

            num = new StringBuffer(), special = new StringBuffer();

            for (int i=0; i<str.length(); i++)

            {

                if (Character.isDigit(str.charAt(i)))

                    num.append(str.charAt(i));

                else if(Character.isAlphabetic(str.charAt(i)))

                    alpha.append(str.charAt(i));

                else

                    special.append(str.charAt(i));

            }

            System.out.println(alpha);

            System.out.println(num);

            System.out.println(special);

        }

        public static void main(String args[])

        {

            String str = "geeks01$$for02geeks03!@!!";

            splitString(str);

        }

    }

    Python3

    def splitString(str):

        alpha = ""

        num = ""

        special = ""

        for i in range(len(str)):

            if (str[i].isdigit()):

                num = num+ str[i]

            elif((str[i] >= 'A' and str[i] <= 'Z') or

                 (str[i] >= 'a' and str[i] <= 'z')):

                alpha += str[i]

            else:

                special += str[i]

        print(alpha)

        print(num )

        print(special)

    if __name__ == "__main__":

        str = "geeks01$$for02geeks03!@!!"

        splitString(str)

    C#

    using System;

    using System.Text;

    class GFG  {

        static void splitString(string str)

        {

            StringBuilder alpha =

                     new StringBuilder();

            StringBuilder num =

                     new StringBuilder();

            StringBuilder special =

                     new StringBuilder();

            for (int i = 0; i < str.Length; i++)

            {

                if (Char.IsDigit(str[i]))

                    num.Append(str[i]);

                else if((str[i] >= 'A' &&

                         str[i] <= 'Z') ||

                         (str[i] >= 'a' &&

                          str[i] <= 'z'))

                    alpha.Append(str[i]);

                else

                    special.Append(str[i]);

            }

            Console.WriteLine(alpha);

            Console.WriteLine(num);

            Console.WriteLine(special);

        }

        public static void Main()

        {

            string str = "geeks01$$for02geeks03!@!!";

            splitString(str);

        }

    }

    Javascript

    <script>

        function splitString(str)

        {

            let alpha = "";

            let num = "";

            let special = "";

            for (let i=0; i<str.length; i++)

            {

                if (!isNaN(String(str[i]) * 1))

                    num+=str[i];

                else if((str[i] >= 'A' && str[i] <= 'Z') ||

                 (str[i] >= 'a' && str[i] <= 'z'))

                    alpha+=str[i];

                else

                    special+=str[i];

            }

            document.write(alpha+"<br>");

            document.write(num+"<br>");

            document.write(special+"<br>");

        }

        let str = "geeks01$$for02geeks03!@!!";

        splitString(str);

    </script>

    Output

    geeksforgeeks
    010203
    $$!@!!

    The time complexity of the above solution is O(n) where n is the length of the string.

    Auxiliary Space: O(n), where n is the length of string.


    How do you separate letters in Python?

    Use the list() class to split a word into a list of letters, e.g. my_list = list(my_str) . The list() class will convert the string into a list of letters. Copied!

    How do you split text and numbers in Python?

    split() method to split a string into text and number, e.g. my_list = re. split(r'(\d+)', my_str) . The re. split() method will split the string on the digits and will still include them in the list.

    How do you split special characters in Python?

    Use the re. split() method to split a string on all special characters. The re. split() method takes a pattern and a string and splits the string on each occurrence of the pattern.

    How do I extract numbers from alphanumeric strings in Python?

    How to extract integers from a string in Python.
    a_string = "0abc 1 def 23".
    numbers = [].
    for word in a_string. split():.
    if word. isdigit():.
    numbers. append(int(word)).
    print(numbers).