10/27/2018

Python String handling tip, remove specific character forward and backward in string

So, this is example code for this processing

input string
__A b c_D___

output string
A b c_D

'_' character is removed in forward and backward.

Refer to code. ๐Ÿค˜
Thank you.

testStr = [' Abc ', ' ', ' ', 'A bc', 'A bc ', ' ', ' a 12 43', ' da ', ' ', 'a2 34', ' 1 2 ']
testStr2 = ['___Abc__', '_', '__', 'A_bc', 'A_bc_', '_____', '_a_12_43', '_da____', '__', 'a2_34', '_1_2_']

def removeTFoward(str, T):
if len(str) == 0:
return str
if str[0] == T:
return removeTFoward(str[1:],T)
else:
return str

def removeTBackword(str, T):
if len(str) == 0:
return str
if str[-1] == T:
return removeTBackword(str[:-1],T)
else:
return str

for n, v in enumerate(testStr2):
str = removeTFoward(v, '_')
str = removeTBackword(str, '_')
if len(str) == 0:
print('nothing')
else:
print(str)


output :
Abc
nothing
nothing
A_bc
A_bc
nothing
a_12_43
da
nothing
a2_34
1_2

No comments:

Post a Comment