博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Python]编程之美
阅读量:6669 次
发布时间:2019-06-25

本文共 2444 字,大约阅读时间需要 8 分钟。

Task 1 : 首字母大写

import re     #python 正则表达式包:res='hello world's=re.sub(r"\w+",lambda match:match.group(0).capitalize(),s)

赏析:

re.sub,实现正则的替换。

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 it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example:>>>>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',...        r'static PyObject*\npy_\1(void)\n{
',... 'def myfunc():')'static PyObject*\npy_myfunc(void)\n{
'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. For example:>>>>>> def dashrepl(matchobj):... if matchobj.group(0) == '-': return ' '... else: return '-'>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')'pro--gram files'>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)'Baked Beans & Spam'The pattern may be a string or an RE object.The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'.In string-type repl arguments, in addition to the character escapes and backreferences described above, \g
will use the substring matched by the group named name, as defined by the (?P
...) syntax. \g
uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE.Changed in version 2.7: Added the optional flags argument.

Pattern  :  r"w+"表示匹配数字和字母下划线的多个字符。

repl  : lambda match:match.group(0).capitalize()表示首字母大写。

转载地址:http://snlxo.baihongyu.com/

你可能感兴趣的文章
backbone 学习之history
查看>>
【Java】数组升序和降序
查看>>
Implement Trie (Prefix Tree)
查看>>
iml文件
查看>>
数据的处理和特征工程
查看>>
DBMS_SCHEDULER CHAIN用法
查看>>
JS实现AOP拦截方法调用
查看>>
文件上传
查看>>
移位操作发现的悲剧
查看>>
win10 nodejs指定ionic版本安装(npm方式)
查看>>
JumpServer跳板机
查看>>
mongodb 与 c++ 的配合使用
查看>>
ios 对齐属性
查看>>
[CDQ分治][Treap][树状数组]JZOJ 4419 Hole
查看>>
HDU - 1078 DP + 记忆化搜索
查看>>
Linux基础命令详解
查看>>
forms组件
查看>>
第十周进度条
查看>>
源码安装node8.11.1
查看>>
bootanimation 动画替换调试
查看>>