+ 2

How can we remove the unnecessary spaces in in a string?

16th Jul 2021, 2:51 PM
Shahir
Shahir - avatar
3 odpowiedzi
+ 9
Shaik.Shahir , removing unnecessary spaces can be removed like this: # split() without argument removes all leading and trailing spaces, also all duplicated spaces, so no extra strip() is needed text = " this is major tom to ground control " print(' '.join(text.split()))
16th Jul 2021, 3:43 PM
Lothar
Lothar - avatar
+ 3
Shaik.Shahir Use replace function abc = "abc def ghi" print (abc.replace(" ", ""))
16th Jul 2021, 3:16 PM
A͢J
A͢J - avatar
+ 1
s = " text with lots of unnecessary spaces" s2 = "***"+s+"***" s3 = '' for i in range(len(s2)): if s2[i]==" " and s2[i-1]==" ": continue elif s2[i]==" " and s2[i-1]=="*": continue else: s3+=s2[i] print(s3[3:-3])
16th Jul 2021, 4:34 PM
Shadoff
Shadoff - avatar