gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:56:17 25 4
gpt4 key购买 nike

我有以下程序:

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 表示整个匹配字符串。

关于python - 如何在空格后将每个单词大写,其余部分保持原样,并在末尾保留空格(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18257605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com