Extracting only characters from a string in Python

前端 未结 7 1162
后悔当初
后悔当初 2020-12-08 07:01

In Python, I want to extract only the characters from a string.

Consider I have the following string,

input = \"{(\'players\',): 24, (\'year\',): 28         


        
相关标签:
7条回答
  • 2020-12-08 07:42

    I think that you want all words, not characters.

    result = re.findall(r"(?i)\b[a-z]+\b", subject)
    

    Explanation:

    "
    \b       # Assert position at a word boundary
    [a-z]    # Match a single character in the range between “a” and “z”
       +        # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
    \b       # Assert position at a word boundary
    "
    
    0 讨论(0)
  • 2020-12-08 07:51

    You could do it with re, but the string split method doesnt take a regex, it takes a string.

    Heres one way to do it with re:

    import re
    word1 = " ".join(re.findall("[a-zA-Z]+", st))
    
    0 讨论(0)
  • 2020-12-08 07:54

    Or if you want all characters regardless of words or empty spaces

        a = "Some57 996S/tr::--!!ing"
        q = ""
        for i in a:
            if i.isalpha():
                q = "".join([q,i])
    

    print q 'SomeString'

    0 讨论(0)
  • 2020-12-08 07:56

    What about doing this?

    >>> import ast
    >>> " ".join([k[0] for k in ast.literal_eval("{('players',): 24, ('year',): 28, ('money',): 19, ('ipod',): 36, ('case',): 23, ('mini',): 46}").keys()])
    'case mini year money ipod players'
    
    0 讨论(0)
  • 2020-12-08 08:01

    string.split() doesn't take regular expressions. You want something like:

    re.split("[^a-zA-Z]*", "your string")
    

    and to get a string:

    " ".join(re.split("[^a-zA-Z]*", "your string"))
    
    0 讨论(0)
  • 2020-12-08 08:01

    You can take the approach of iterating through the string, and using the isalpha function to determine if it's a alpha character or not. If it is you can append it to the output string.

    a = "Some57 996S/tr::--!!ing"
    q = ""
    for i in a:
        if i.isalpha():
            q = "".join([q,i])
    
    0 讨论(0)
提交回复
热议问题