Python:获取两个大写字母之间的字符串



我想听听你的意见,因为你可能和我一样对Python更有经验。

我来自C++,但我仍然不习惯Python的做事方式。我想在两个大写字母之间的字符串下循环。例如,我可以这样做:

 i = 0
 str = "PythonIsFun"
 for i, z in enumerate(str):
     if(z.isupper()):
         small = ''
         x = i + 1
         while(not str[x].isupper()):
             small += str[x]

我在手机上写的,所以我不知道这是否有效,但我想你已经明白了。我需要你帮助我在这方面获得最好的结果,不仅仅是以非强制的方式对cpu,还有干净的代码。非常感谢

这是正则表达式是最佳选择的时候之一。

(顺便说一句,不要调用字符串str:它隐藏了内置函数。)

s = 'PythonIsFun'
result = re.search('[A-Z]([a-z]+)[A-Z]', s)
if result is not None:
    print result.groups()[0]

您可以使用正则表达式:

import re
re.findall ( r'[A-Z]([^A-Z]+)[A-Z]', txt )

输出['ython']

re.findall ( r'(?=[A-Z]([^A-Z]+)[A-Z])', txt )

输出CCD_ 3;如果你只需要第一场比赛,

re.search ( r'[A-Z]([^A-Z]+)[A-Z]', txt ).group( 1 )

您可以使用列表理解来轻松做到这一点。

>>> s = "PythonIsFun"
>>> u = [i for i,x in enumerate(s) if x.isupper()]
>>> s[u[0]+1:u[1]]
'ython'

如果你不能保证有两个大写字符,你可以检查u的长度,以确保它至少是2。这确实会迭代整个字符串,如果两个大写字符出现在一个长字符串的开头,这可能会产生问题。

有很多方法可以解决这个问题,但我会使用正则表达式。

此示例将使用"PythonIsFun"并返回"ythonsun"

import re
text = "PythonIsFun"
pattern = re.compile(r'[a-z]')      #look for all lower-case characters
matches = re.findall(pattern, text) #returns a list of lower-chase characters
lower_string = ''.join(matches)     #turns the list into a string
print lower_string

输出:

ythonsun

相关内容

最新更新