Skip to main content
 首页 » 编程设计

python之如何在空格后将每个单词大写,其余部分保持原样,并在末尾保留空格(如果存在)

2024年11月01日9unruledboy

我有以下程序:

def capitalize(self, text): 
    t = ' '.join([ ''.join([w[0].upper()]+[w[1:]]) for w in text.split()]) 
    if text and text[-1] == ' ': 
        t = ''.join([t] + [' ']) 
    return t 

它接受一个字符串文本。 它应该做什么:

  • 将空格后的每个字符串组(单词)的第一个字母大写,并在文本末尾保留空格(如果提供)。

例如:

'home swe eeeet home' -> 'Home Swe Eeeet Home' 
'heLLo OoO ooo '      -> 'HeLLo OoO Ooo ' (space preserved in the end) 

问题:

由于我的 Python 水平有限,完全非专家水平,我试图尽可能快地创建这个过程,以尽可能节省内存。

  • 在这种情况下,将事物转换为列表并将它们加入到不继续创建新字符串的方法是否有效?

  • 是否有更好、更 pythonic 的方法来实现这一目标?

此外:

每次在 GUI 应用程序的文本字段上按下一个键时都会调用此过程。

请您参考如下方法:

使用re.sub :

>>> import re 
>>> re.sub(r'\b[a-z]', lambda m: m.group().upper(), 'home swe eeeet home') 
'Home Swe Eeeet Home' 
>>> re.sub(r'\b[a-z]', lambda m: m.group().upper(), 'heLLo OoO ooo ') 
'HeLLo OoO Ooo ' 

re.sub(pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function.

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

\b[a-z] 匹配单词边界 (\b) 之后的任何小写字符 ([a-z])。

lambda 函数用于将字符转换为大写; MatchObject.match返回匹配组。假设没有参数组 0。组 0 表示整个匹配字符串。