我在这里解决了这个问题,https://www.hackerrank.com/challenges/capitalize
描述:给你一个字符串。你的任务是将其中的每个单词大写。简而言之,只有第一个字符是大写的。示例12abc当大写时仍然是12abc -因为这个'title‘不能正确使用像'1 w 2 r 3g’这样的字符串。我需要检查数字和小写字母的组合。这是我的代码:
def capitalize(string):
result = list (string.title())
for index in range (len (string)-1):
if string[index].isdigit () and string[index+1].islower ():
result[index+1] = result[index+1].lower()
result = ''.join([char for char in result])
return (result)但是这段代码太麻烦了。有人能帮助你做出更优雅的蟒蛇决策吗?谢谢!
发布于 2017-02-25 17:13:45
re模块可以在这里提供帮助:
titlesub = re.compile(r'\b[a-zA-Z]').sub # Precompile regex and prebind method for efficiency
def capitalize(string):
return titlesub(lambda x: x.group(0).upper(), string)注意:\b处理单词/非单词字符的边界(单词字符是字母数字和下划线),因此它将阻止12abc将a大写,但它不会对"abc (变为"Abc)执行此操作。
虽然\b很方便,但它确实意味着像"won't"这样的字符串将被大写为"Won'T"。如果这是一个问题,当前面没有非空格字符时,可以使用一个更有针对性的选择器来大写:
titlesub = re.compile(r'(?<!\S)[a-zA-Z]').sub发布于 2017-02-25 17:06:49
' '.join([x.capitalize() for x in s.split(' ')])发布于 2017-02-25 17:13:39
您可以使用re模块
import re
someStr = '1 w 2 r 3ga hello world'
re.sub(r"(?<=[0-9])[a-zA-Z]", lambda m: m.group(0).lower(), someStr.title())输出:
# 1 W 2 R 3ga Hello Worldpositive look-behind (?<=[0-9])仅匹配前面有数字的字母字符([a-zA-Z])。对于这些匹配,我们使用.lower()方法来“撤销”.title()的效果
https://stackoverflow.com/questions/42453979
复制相似问题