I have a dictionary. There are some space infant of keys. How I can remove all of these space and keep only one space infant of keys? I made the dictionary with the following code:
def get_JobAbbreviation_data():
data=pd.read_csv('A.csv')
data=data.replace(u'\xa0', u'', regex=True)
data.dropna(inplace=True)
Title = data['FIRST'].str.lower()+' '
Abbr = data['1ST'].str.lower()+ ' '
JobAbbreviation=dict(zip(Abbr, Title))
return JobAbbreviation
This breaks down to "How to remove all (but one) spaces at the start of a string"?
Removing spaces is easy:
In [1]: " abcd".lstrip()
Out[1]: 'abcd'
Then, just add a space, so... " " + mystring.lstrip()
.
That's the building block. The next part of the question is: "How to apply this to all the keys?":
Abbr = [" " + s.lstrip() for s in Abbr]
Then build your dictionary.
I assume by "infant" you actually mean "in front". If you have a dictionary that looks as follows:
dct = {" Three Spaces": 3, " Four Spaces": 4, " One Space": 1, "Zero Spaces": 0}
And you want this exact same dictionary where all the keys have only 1 white space at the start, you can do it as follows:
dctKeys = list(map((lambda x: " " + x.strip()) , [*dct.keys()]))
finDct = dict(zip(dctKeys, dct.values()))
finDct
This output will be the following:
{' Four Spaces': 4, ' One Space': 1, ' Three Spaces': 3, ' Zero Spaces': 0}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.