简体   繁体   English

Python:在使用str.lower时,如何避免使用小写字符串中的特定单词

[英]Python: How can i avoid specific word in string from lowercasing while using str.lower

Iam new to python 我刚接触python

i have a list of string as follws 我有一个字符串列表作为follws

mylist=["$(ProjectDir)Dir1\Dest1","$(OutDir)Dir2\Dest2","$(IntDir)Dir2\Dest2"]

i want to lower case each list item value as follows 我想小写每个列表项值如下

mylist=["$(ProjectDir)dir1\dest1","$(OutDir)dir2\dest2","$(IntDir)dir3\dest3"]

ie i want to prevent $(ProjectDir) , $(OutDir) , $(IntDir) from lowercasing 即我想$(OutDir)防止$(ProjectDir)$(OutDir)$(IntDir)

The idea is very simple. 这个想法非常简单。 You split the string with a regular expression describing parts that are not to be converted, then convert only its even parts, then join them back. 您使用描述不要转换的部分的正则表达式拆分字符串,然后仅转换其偶数部分,然后将它们连接起来。

>>> import re
>>> mylist=["$(ProjectDir)Dir1\Dest1","$(OutDir)Dir2\Dest2","$(IntDir)Dir2\Dest2"]
>>> print ["".join([s if i%2 else s.lower()  for (i,s) in enumerate(re.split('(\$\([^)]*\))', x))]) for x in mylist]
['$(ProjectDir)dir1\\dest1', '$(OutDir)dir2\\dest2', '$(IntDir)dir2\\dest2']

The main thing here is: 这里最重要的是:

[ "".join([
     s if i%2 else s.lower()
     for (i,s) in enumerate(re.split('(\$\([^)]*\))', x))])
   for x in mylist ]

You go through the list mylist and for every x produce it modified version: 您浏览列表mylist并为每个x生成它修改版本:

[ ... for x in mylist ]

You convert every x using this operation: 您使用此操作转换每个x

"".join([
     s if i%2 else s.lower()
     for (i,s) in enumerate(re.split('(\$\([^)]*\))', x))]

That means: split the string to parts that must be converted (even) and must not be converted (odd). 这意味着:将字符串拆分为必须转换的部分(偶数),不得转换(奇数)。

For example: 例如:

>>> re.split('(\$\([^)]*\))', x)
['', '$(ProjectDir)', 'Dir1\\Dest1']

and than enumerate them and convert all even parts: 而不是枚举它们并转换所有偶数部分:

>>> print list(enumerate(re.split('(\$\([^)]*\))', x)))
[(0, ''), (1, '$(ProjectDir)'), (2, 'Dir1\\Dest1')]

If a part is even or odd you check using this if : 如果一个部分是奇数还是偶数您检查使用这个if

 s if i%2 else s.lower()

If you are allergic to regular expressions... 如果你对正则表达过敏...

exclusions = ['$(ProjectDir)', '$(OutDir)', '$(IntDir)']
mylist = ["$(ProjectDir)Dir1\Dest1", "$(OutDir)Dir2\Dest2", "$(IntDir)Dir2\Dest2"]

## Lower case everything
mylist = [s.lower() for s in mylist]

## Revert the exclusions
for patt in exclusions:
    mylist = [s.replace(patt.lower(), patt) for s in mylist]

print mylist

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

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