-3

I need to retain only lowercase text and underscore in a string and replace everything else with space(" ").

say input: text List ? this_word. required output: text ist this_word

I am trying the regex expression ^[a-z_] but this doesn't seem to work

karthik_ghorpade
  • 374
  • 1
  • 10

2 Answers2

0

Here you are:

[^a-z_\s]

Test the regex here

import re

regex = r"[^a-z_\s]"

test_str = " text List ? this_word."

subst = ""

result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

Output:

 text ist  this_word

Test the code here

totok
  • 1,436
  • 9
  • 28
  • 1
    Thanks a lot. I couldn't it figure it out because I am only just learning regex. – karthik_ghorpade Aug 18 '20 at 07:25
  • 1
    Here is a really good start to learn Regex : [article](https://stackoverflow.com/questions/4736/learning-regular-expressions), and you can experiment on [regex101.com](https://regex101.com/): they are challenges, a test editor, and a code generator for python if you need it – totok Aug 18 '20 at 07:34
0
string = "aBcDeFgH"
new_string = []

for char in string:
    if char.islower() or char == "_":
        new_string.append(char)
    else:
        new_string.append(" ")

print(''.join(new_string))

OUTPUT:

a c e g 
Gavin Wong
  • 1,254
  • 1
  • 6
  • 15