![](/img/trans.png)
[英]Most Pythonic and efficient way to insert character at end of string if not already there
[英]Pythonic way to insert character
我有两个转换案例:
s = "foo bar" #-> "foo bar &"
s = "foo ! bar" # -> "foo & ! bar" -> notice not '&!'
我是这样做的:
t = s.split("!", 1)
t[0] = t[0] + " &"
" !".join(t)
什么是更加pythonic的方式来做同样的事情?
不确定这是否更加pythonic,但上面的例子可以作为一个单行。
>>> s = "foo ! bar"
>>> s = s.replace(' ! ', ' & ! ') if '!' in s else s + ' &'
>>> s
'foo & ! bar'
str.partition
是为运算符解析而构建的:
p = s.partition(' !')
print p[0]+' &'+p[1]+p[2]
当从左到右解析时,它适用于前缀和中缀运算符。 它总是返回一个3元组的事实允许使用它,即使找不到你的操作符并对你的结果应用一个动作,如上所示。
>>> import re
>>> re.sub(r'( !|$)', r' &\1', 'foo bar', 1)
'foo bar &'
>>> re.sub(r'( !|$)', r' &\1', 'foo ! bar', 1)
'foo & ! bar'
在一行中执行多个句子:
>>> s = ["foo bar", "foo ! bar"]
>>> [x + ' &' if not '!' in x else x.replace('!','& !', 1) for x in s]
['foo bar &', 'foo & ! bar']
s1 = "foo bar"
s2 = "foo ! bar"
import re
print re.sub(r'^([^!]+)( |$)', r'\1 &\2', s1) # foo bar &
print re.sub(r'^([^!]+)( |$)', r'\1 &\2', s2) # foo & ! bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.