打印字符串中两个大写字母之间的子字符串



这是我的代码:

x = str(input())
w = ' '
w2 = ''
for i in x:
    if i.isupper() == True:
        w2 += w
    else:
        w2 += i
print(w2)

我已经将大写字母转换为空格,有人能建议我下一步该怎么做吗?

输入:abCdefGh
预期输出:def

打印字符串中两个大写字母之间的子字符串。

步骤1:找到大写字母的索引位置。

步骤2:然后将列表中第一个元素+1和第二个元素之间的子字符串切片(string[start:end](

word = "abCdefGh"
# Get indices of the capital letters in a string:
def getindices(word):
    indices = []
    for index, letter in enumerate(word):
        if (letter.isupper() == True):
            indices.append(index)
    return indices

if __name__ == "__main__":
    caps_indices = getindices(word)
    start = caps_indices[0] + 1
    end = caps_indices[1]
    print(word[start:end])

输出:

def

我使用一个标志来标记程序是否应该将字符i添加到w2中。注意我写的条件。它是我代码的关键。

x = "abCdefGh"
w2 = ''
inBetween = False
for i in x:
    if i.isupper():
        # Upper case denotes either start or end of substring
        if not inBetween:
            # start of substring
            inBetween = True
            continue
        else:
            # end of substring
            inBetween = False
            break
    if inBetween:
        w2+= i
print(w2)

结果是:

def

您可以使用regex轻松提取文本。

import re
# pattern to accept everything between the capital letters.
pattern = '[A-Z](.*?)[A-Z]'
# input string
input_string= 'thisiSmyString'
    
matched_string = re.findall(pattern, input_string)
print(matched_string[0])

相关内容

最新更新