Python 字符串大写
Python String Capitalize
from string import capwords
t = "\"i'm happy,\" said tanby"
sText = t.split()
rText = []
for str in sText:
if '\"' in str[0]:
t = capwords(str, sep='\"')
rText.append(t)
else:
t = capwords(str)
rText.append(t)
print(' '.join(rText))
>>> "I'm Happy," Said Tanby
^ ^ ^ ^
忽略引号并大写。
使用 title()
时,变为 " I'M,使用 capwords()
时,变为 " i'm。
有没有更好的方法?
引号干扰 capwords
算法。将 re.sub
与允许在单词中使用单引号的模式一起使用可以修复它。正则表达式匹配一个或多个 \w
(单词字符)或单引号。每个匹配项都传递给 lambda 函数并大写以进行替换。
>>> import re
>>> s='"i\'m happy," said tanby'
>>> print(re.sub(r"\b[\w']+\b",lambda m: m.group().capitalize(),s))
"I'm Happy," Said Tanby
from string import capwords
t = "\"i'm happy,\" said tanby"
sText = t.split()
rText = []
for str in sText:
if '\"' in str[0]:
t = capwords(str, sep='\"')
rText.append(t)
else:
t = capwords(str)
rText.append(t)
print(' '.join(rText))
>>> "I'm Happy," Said Tanby
^ ^ ^ ^
忽略引号并大写。
使用 title()
时,变为 " I'M,使用 capwords()
时,变为 " i'm。
有没有更好的方法?
引号干扰 capwords
算法。将 re.sub
与允许在单词中使用单引号的模式一起使用可以修复它。正则表达式匹配一个或多个 \w
(单词字符)或单引号。每个匹配项都传递给 lambda 函数并大写以进行替换。
>>> import re
>>> s='"i\'m happy," said tanby'
>>> print(re.sub(r"\b[\w']+\b",lambda m: m.group().capitalize(),s))
"I'm Happy," Said Tanby