[英]remove white space before a string character
I am having difficulty removing white space in front of the character. 我在删除角色前面的空白时遇到困难。 I am trying to parse the sample string object below:
我正在尝试解析下面的示例字符串对象:
Mary Whitten: {laptop: 100, tv : 5, xbox: 50, }, James Doe: {laptop: 30, tv: 3, xbox: 5,}, Jesus Navas: {laptop: 25, tv: 3, xbox: 5},Matt Mart:{laptop:10, xbox: 10}
i also used .split('},') while parsing the above string. 在解析上述字符串时,我还使用了.split('},')。 The keys that I got:
我得到的钥匙:
d=['Mary Whitten', ' James Doe', ' Jesus Navas', 'Matt Mart']
there are some white spaces in front of ' James Doe' and ' Jesus Navas' which I am trying to avoid because keys are sensitive to white spaces ie d['James Doe'] is not same as [' James Doe'] because of the white space in the key. 我试图避免在'James Doe'和'Jesus Navas'前面有一些空格,因为密钥对空格敏感,即d ['James Doe']与['James Doe']不同,原因是键中的空白。 How would I avoid it?
我要如何避免呢? Also, I wanted to make the list items case insensitive like:
另外,我想使列表项不区分大小写,例如:
d=(items.lowercase() for items in d)
Look at strip()
, lstrip()
and rstrip()
. 查看
strip()
, lstrip()
和rstrip()
。 Docs here . 文档在这里 。
For example: 例如:
>>> 'Mary Whitten '.rstrip()
'Mary Whitten'
>>> ' James Doe'.lstrip()
'James Doe'
>>> ' Jesus Navas '.strip()
'Jesus Navas'
If you only want certain characters stripped (such as only whitespace), you can feed the .*strip
methods a character or iterable of characters, such as .strip(" ")
or '.rstrip("\\?\\.\\!\\n")
. 如果只希望删除某些字符(例如仅空格),则可
.strip(" ")
.*strip
方法提供一个字符或可迭代的字符,例如.strip(" ")
或'.rstrip("\\?\\.\\!\\n")
。
For your purpose, it looks like 为了您的目的,它看起来像
d = (items.lower().strip() for items in d)
You can simply do that as follows: 您可以按照以下步骤简单地进行操作:
string.strip()
Running this script on " Hello "
would give "Hello"
在
" Hello "
上运行此脚本将得到"Hello"
For your code, you would do it as follows: 对于您的代码,您可以按照以下步骤进行操作:
d = [item.strip() for item in d]
>>> d = (item.lower().strip() for item in d)
>>> print d
['mary whitten', 'james doe', 'jesus navas', 'matt mart']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.