Kul*_*ini 1 ruby python string strip
在Python中,我可以从字符串中删除空格,新行或随机字符
>>> '/asdf/asdf'.strip('/')
'asdf/asdf' # Removes / from start
>>> '/asdf/asdf'.strip('/f')
'asdf/asd' # Removes / from start and f from end
>>> ' /asdf/asdf '.strip()
'/asdf/asdf' # Removes white space from start and end
>>> '/asdf/asdf'.strip('/as')
'df/asdf' # Removes /as from start
>>> '/asdf/asdf'.strip('/af')
'sdf/asd' # Removes /a from start and f from end
Run Code Online (Sandbox Code Playgroud)
但Ruby的String#strip方法不接受任何参数.我总是可以回到使用正则表达式,但有没有一种方法/方法从Ruby中的字符串(后面和前面)中删除随机字符而不使用正则表达式?
您可以使用正则表达式:
"atestabctestcb".gsub(/(^[abc]*)|([abc]*$)/, '')
# => "testabctest"
Run Code Online (Sandbox Code Playgroud)
当然你也可以把它变成一个方法:
def strip_arbitrary(s, chars)
r = chars.chars.map { |c| Regexp.quote(c) }.join
s.gsub(/(^[#{r}]*)|([#{r}]*$)/, '')
end
strip_arbitrary("foobar", "fra") # => "oob"
Run Code Online (Sandbox Code Playgroud)