簡體   English   中英

在字符串上找到大寫字母並替換它

[英]find the uppercase letter on a string and replace it

這是我的代碼:

def cap_space(txt):
    e = txt
    upper = "WLMFSC"
    letters = [each for each in e if each in upper]
    a = ''.join(letters)
    b = a.lower()
    c = txt.replace(a,' '+b)
    return c

我建立了誰來查找給定字符串上的大寫后者並將其替換為空格和后者的小寫

示例輸入:

print(cap_space('helloWorld!'))
print(cap_space('iLoveMyFriend'))
print(cap_space('iLikeSwimming'))
print(cap_space('takeCare'))

output 應該是什么樣的:

hello world!
i love my friend
take care
i like swimming

我得到的 output 是:

hello world!
iLoveMyFriend
iLikeSwimming
take care

這里的問題是該條件僅適用於給定字符串中只有一個大寫字母的情況,出於某種原因,我如何改進它以使其應用於給定字符串上的每個大寫字母?

作為一個正則表達式迷,我可以提供以下解決方案,它依賴於具有適當正則表達式模式的re.findall

def cap_space(txt):
    parts = re.findall(r'^[a-z]+|[A-Z][a-z]*[^\w\s]?', txt)
    output = ' '.join(parts).lower()
    return output

inp = ['helloWorld!', 'iLoveMyFriend', 'iLikeSwimming', 'akeCare']
output = [cap_space(x) for x in inp]
print(inp)
print(output)

這打印:

['helloWorld!', 'iLoveMyFriend', 'iLikeSwimming', 'akeCare']
['hello world!', 'i love my friend', 'i like swimming', 'ake care']

以下是使用的正則表達式模式的解釋:

^[a-z]+   match an all lowercase word from the very start of the string
|         OR
[A-Z]     match a leading uppercase letter
[a-z]*    followed by zero or more lowercase letters
[^\w\s]?  followed by an optional "symbol" (defined here as any non word,
                                            non whitespace character)

一種簡單粗暴的方式。 它可能無效,但更容易理解

def cap_space(sentence):
    characters = []
    for character in sentence:
        if character.islower():
            characters.append(character)
        else:
            characters.append(f' {character.lower()}')
    return ''.join(characters)

您可以使用不錯的python3方法str.translatestr.maketrans

In [281]: def cap_space(txt):
     ...:     upper = "WLMFSC"
     ...:     letters = [each for each in txt if each in upper]
     ...:     d = {i: ' ' + i.lower() for i in letters}
     ...:     return txt.translate(str.maketrans(d))
     ...: 
     ...: 

In [283]: print(cap_space('helloWorld!'))
     ...: print(cap_space('iLoveMyFriend'))
     ...: print(cap_space('iLikeSwimming'))
     ...: print(cap_space('takeCare'))
hello world!
i love my friend
i like swimming
take care

a是所有匹配的大寫字母組合成一個字符串。 當您嘗試用txt.replace(a, ' '+b)替換它們時,它只會匹配所有匹配的大寫字母在txt中是連續的,或者只有一個匹配。 str.replace()匹配並替換整個 seawrch 字符串,而不是其中的任何字符。

將所有匹配項組合成一個字符串是行不通的。 只需遍歷txt ,檢查每個字符是否匹配。

def cap_space(txt):
    result = ''
    upper = "WLMFSC"
    for c in txt:
        if c in upper:
            result += ' ' + c.lower()
        else:
            result += c
    return result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM