Home > Blockchain >  Removing Single Character Substring and Not in List
Removing Single Character Substring and Not in List

Time:05-18

I can effectively remove single characters from source_string, however how do I include the condition to not remove single characters that are in the list compass?

compass = ['N', 'E', 'S', 'W']
source_string = 'Florida W Campus A B CD'
' '.join([x for x in source_string.split() if (len(x)>1)])

>>> 'Florida Campus CD'

Desired Result:

>>> 'Florida W Campus'

Edit: I need to add multiple characters in string 'Florida W Campus A B CD'

CodePudding user response:

Try:

>>> ' '.join([x for x in source_string.split() if (len(x)>1) or x in compass])
'Florida W Campus CD'

CodePudding user response:

You may use:

compass = ['N', 'E', 'S', 'W']
addl_strs = ['A', 'B', 'CD']
keep_strs = set(compass).union(set(addl_strs))
' '.join(list(filter(lambda x:len(x) > 1 if x not in keep_strs else x, source_string.split())))

You can add more strings if you want using another list and form a set to see if its there to check length.

CodePudding user response:

compass = ['N', 'E', 'S', 'W']
source_string = 'Florida W Campus A B'
' '.join([x for x in source_string.split() if x in compass or (len(x)>1)])
  • Related