简体   繁体   English

如何从字典键的前面删除多余的空间?

[英]how to remove extra space from infront of a dictionary's keys?

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() .然后,只需添加一个空格,所以... " " + 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:你想要这个完全相同的字典,其中所有的键在开始时只有 1 个空格,你可以这样做:

dctKeys = list(map((lambda x: " " + x.strip()) , [*dct.keys()]))
finDct = dict(zip(dctKeys, dct.values()))
finDct

This output will be the following:这个 output 将如下:

{' Four Spaces': 4, ' One Space': 1, ' Three Spaces': 3, ' Zero Spaces': 0}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM