插入字符的 Pythonic 方式

标签 python string

我有两个转换案例:

s = "foo bar" #-> "foo bar &"
s = "foo ! bar" # -> "foo & ! bar" -> notice not '&!'

我是这样做的:

t = s.split("!", 1)
t[0] = t[0] + "  &"
" !".join(t)

有什么更 pythonic 的方法来做同样的事情?

最佳答案

str.partition 是为了运算符解析而构建的:

p = s.partition(' !')
print p[0]+' &'+p[1]+p[2]

它适用于从左到右解析时的前缀和中缀运算符。事实上,它总是返回一个 3 元组,即使在找不到您的运算符时也可以使用它,并对您的结果应用操作,如上所示。

关于插入字符的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10669665/

相关文章:

Python3 迭代器与生成器

python - 清除Python请求中的所有cookie

在C中将字符串的尾部复制到另一个数组中,无引用无指针

c++ - 我不确定为什么我的字符串只显示字符串的第一个字符

c++ - 像 printf 函数一样构建字符串

Python 错误处理程序 : Creating a sublist of floats from list of strings

python - 如何在 Python 中使用 Google 的文本转语音 API

Python CSV : Grab all values in row with conditions for time values

c++ - 为什么我不能在 C++ 中将此方法与 'char' 而不是 'string' 方法一起使用?

c - 字符串反转功能不起作用