Python remove spaces from a string
Today these tutorials are various ways to remove spaces from a string in Python. This tutorial provides a short example of various functions we can use to remove whitespaces from a string. here this tutorials in strip(),rstrip(),lstrip(),replace(),join(),split(),translate() python in-built function use.
Let’s say we have an example:
strip()
strip() function will remove leading and trailing whitespaces of the string.
>>> str = ' Python remove \n\r\t spaces from string ' >>> str.strip() output : 'Python remove \n\r\t spaces from string'
rstrip()
rstrip() function removed the white spaces from right side of the string.
>>> str = ' Python remove \n\r\t spaces from string ' >>> str.rstrip() output : ' Python remove \n\r\t spaces from string'
lstrip()
lstrip() function remove the white spaces from the left side of the string.
>>> str = ' Python remove \n\r\t spaces from string ' >>> str.lstrip() output : 'Python remove \n\r\t spaces from string '
replace()
replace() remove all the whitespaces from the string a string by replacing some parts of another string.
>>> str = ' Python remove \n\r\t spaces from string ' >>> str.replace(" ", "") output : 'Pythonremove\n\r\tspacesfromstring'
join()
join() method to create a string. and join all the iterable elements with a string as delimiter.
Strings to CSV
>>> delimiter = "," >>> csv_str = delimiter.join(['x', 'y', 'z']) >>> print(csv_str) output : x,y,z
Concatenation of the Strings
>>> vowels = ('d', 'e', 'v', 'n', 'o', 't', 'e') >>> vowels_str = "".join(vowels) >>> print(vowels_str) output : devnote
join() with Single String
>>> string = 'Devnote' >>> print(f'String : {",".join(string)}') output : String : D,e,v,n,o,t,e
split()
split() function is utilized to part a string into the rundown of strings dependent on a delimiter.
>>> str = 'Devnote is Nice tutorial' >>> str_list = str.split(sep=' ') >>> print(str_list) output : ['Devnote', 'is', 'Nice', 'tutorial']
join() with split()
>>> str = ' Python remove \n\r\t spaces from string ' >>> " ".join(str.split()) output : 'Python remove spaces from string'
translate()
translate() function returns new string with each character in the string replaced.
>>> str = ' Python remove \n\r\t spaces from string ' >>> import string >>> str.translate({ord(c): None for c in string.whitespace}) output : 'Pythonremovespacesfromstring'