2

Getting a string that comes after a '%' symbol and should end before other characters (no numbers and characters). for example:

string = 'Hi %how are %YOU786$ex doing'

it should return as a list.

['how', 'you']

I tried

string = text.split()

sample = []

for i in string:
    if '%' in i:
        sample.append(i[1:index].lower())
return sample

but it I don't know how to get rid of 'you786$ex'. EDIT: I don't want to import re

1
  • Have you looked into regular expressions? Commented Nov 19, 2018 at 18:34

3 Answers 3

3

You can use a regular expression.

>>> import re
>>> 
>>> s = 'Hi %how are %YOU786$ex doing'
>>> re.findall('%([a-z]+)', s.lower())
>>> ['how', 'you']

regex101 details

Sign up to request clarification or add additional context in comments.

Comments

1

This can be most easily done with re.findall():

import re
re.findall(r'%([a-z]+)', string.lower())

This returns:

['how', 'you']

Or you can use str.split() and iterate over the characters:

sample = []
for token in string.lower().split('%')[1:]:
    word = ''
    for char in token:
        if char.isalpha():
            word += char
        else:
            break
    sample.append(word)

sample would become:

['how', 'you']

Comments

0

Use Regex (Regular Expressions).

First, create a Regex pattern for your task. You could use online tools to test it. See regex for your task: https://regex101.com/r/PMSvtK/1

Then just use this regex in Python:

import re

def parse_string(string):
    return re.findall("\%([a-zA-Z]+)", string)

print(parse_string('Hi %how are %YOU786$ex doing'))

Output:

['how', 'YOU']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.