How can I fill out a Python string with spaces?
You can do this with str.ljust(width[, fillchar])
:
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than
len(s)
.
>>> 'hi'.ljust(10)
'hi '
How to pad a string to a fixed length with spaces in Python?
This is super simple with format
:
>>> a = "John"
>>> "{:<15}".format(a)
'John '
Python - How can I pad a string with spaces from the right and left?
You can look into str.ljust
and str.rjust
I believe.
The alternative is probably to use the format method:
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
How do I convert a list into a string with spaces in Python?
" ".join(my_list)
You need to join with a space, not an empty string.
how to search a string with spaces within another string in python?
You can also use a regex approach like this:
import re
Glist={'masked 111', 'DATA',"My Add no" , 'MASKEDDATA',}
glst_rx = r"\b(?:{})\b".format("|".join(Glist))
def garbagefin(x):
if re.search(glst_rx, x, re.I):
return ''
else:
return x
See the Python demo.
The glst_rx = r"\b(?:{})\b".format("|".join(Glist))
code will generate the \b(?:My Add no|DATA|MASKEDDATA|masked 111)\b
regex (see the online demo).
It will match the strings from Glist
in a case insensitive way (note the re.I
flag in re.search(glst_rx, x, re.I)
) as whole words, and once found, an empty string will be returned, else, the input string will be returned.
If there are too many items in Glist
, you could leverage a regex trie (see here how to use the trieregex
library to generate such tries.)
Related Topics
Best Way to Return Multiple Values from a Function
"Large Data" Workflows Using Pandas
How to Have One Colorbar For All Subplots
Find Unique Rows in Numpy.Array
Pip Install Failing With: Oserror: [Errno 13] Permission Denied on Directory
Convert List of Dictionaries to a Pandas Dataframe
Pygame Window Not Responding After a Few Seconds
Remove Specific Characters from a String in Python
Use Numpy Array in Shared Memory For Multiprocessing
"Ask Forgiveness Not Permission" - Explain
How to Read Large Text Files Line by Line, Without Loading It into Memory