简体   繁体   English

在字符串上找到大写字母并替换它

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

This is my code:这是我的代码:

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

who i built to find the uppercase latters on a given string and replace it with space and the lowercase of the latter我建立了谁来查找给定字符串上的大写后者并将其替换为空格和后者的小写

example input:示例输入:

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

what should output be like: output 应该是什么样的:

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

what i get as output instead is:我得到的 output 是:

hello world!
iLoveMyFriend
iLikeSwimming
take care

the problem here is the condition only applied if there only one upper case latter in the given string for some reasons how i could improve it to get it applied to every upper case latter on the given string?这里的问题是该条件仅适用于给定字符串中只有一个大写字母的情况,出于某种原因,我如何改进它以使其应用于给定字符串上的每个大写字母?

Being a regex addict, I can offer the following solution which relies on re.findall with an appropriate regex pattern:作为一个正则表达式迷,我可以提供以下解决方案,它依赖于具有适当正则表达式模式的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)

This prints:这打印:

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

Here is an explanation of the regex pattern used:以下是使用的正则表达式模式的解释:

^[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)

A simple and crude way.一种简单粗暴的方式。 It might not be effective but it is easier to understand它可能无效,但更容易理解

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

You can make use of nice python3 methodsstr.translate and str.maketrans :您可以使用不错的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 is all the matching uppercase letters combined into a single string. a是所有匹配的大写字母组合成一个字符串。 When you try to replace them with txt.replace(a, ' '+b) , it will only match if all the matchinguppercase letters are consecutive in txt , or there's just a single match.当您尝试用txt.replace(a, ' '+b)替换它们时,它只会匹配所有匹配的大写字母在txt中是连续的,或者只有一个匹配。 str.replace() matches and replaces the whole seawrch string, not any characters in it. str.replace()匹配并替换整个 seawrch 字符串,而不是其中的任何字符。

Combining all the matches into a single string won't work.将所有匹配项组合成一个字符串是行不通的。 Just loop through txt , checking each character to see if it matches.只需遍历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