>>> ' Hello '.strip()'Hello'>>> ' Hello'.strip()'Hello'>>> 'Bob has a cat'.strip()'Bob has a cat'>>> ' Hello '.strip() # ALL consecutive spaces at both ends removed'Hello'
def cleansed(s: str):""":param s: String to be cleansed"""assert s is not (None or "")# return trimmed(s.replace('"', '').replace("'", ""))return trimmed(s)
def trimmed(s: str):""":param s: String to be cleansed"""assert s is not (None or "")ss = trim_start_and_end(s).replace(' ', ' ')while ' ' in ss:ss = ss.replace(' ', ' ')return ss
def trim_start_and_end(s: str):""":param s: String to be cleansed"""assert s is not (None or "")return trim_start(trim_end(s))
def trim_start(s: str):""":param s: String to be cleansed"""assert s is not (None or "")chars = []for c in s:if c is not ' ' or len(chars) > 0:chars.append(c)return "".join(chars).lower()
def trim_end(s: str):""":param s: String to be cleansed"""assert s is not (None or "")chars = []for c in reversed(s):if c is not ' ' or len(chars) > 0:chars.append(c)return "".join(reversed(chars)).lower()
s1 = ' b Beer 's2 = 'Beer b 's3 = ' Beer b 's4 = ' bread butter Beer b '
cdd = trim_start(s1)cddd = trim_end(s2)clean1 = cleansed(s3)clean2 = cleansed(s4)
print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s1, len(s1), cdd, len(cdd)))print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s2, len(s2), cddd, len(cddd)))print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s3, len(s3), clean1, len(clean1)))print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s4, len(s4), clean2, len(clean2)))
def remove_outer_spaces(text, num_of_leading, num_of_trailing):text = list(text)for i in range(num_of_leading):if text[i] == " ":text[i] = ""else:break
for i in range(1, num_of_trailing+1):if text[-i] == " ":text[-i] = ""else:breakreturn ''.join(text)
txt1 = " MY name is "print(remove_outer_spaces(txt1, 1, 1)) # result is: " MY name is "print(remove_outer_spaces(txt1, 2, 3)) # result is: " MY name is "print(remove_outer_spaces(txt1, 6, 8)) # result is: "MY name is"
words=input("Enter the word to test")# If I have a user enter discontinous threads it becomes a problem# input = " he llo, ho w are y ou "n=words.strip()print(n)# output "he llo, ho w are y ou" - only leading & trailing spaces are removed
def whitespace(words):r=words.replace(' ','') # removes all whitespacen=r.replace(',','|') # other uses of replacereturn ndef run():words=input("Enter the word to test") # take user inputm=whitespace(words) #encase the def in run() to imporve usability on various functionso=m.count('f') # for testingreturn m,oprint(run())output- ('hello|howareyou', 0)