I will be updating this as I go… but see also the Wikipedia page on string functions in various languages.
Joining a string list
-- Python: ",".join(lst) -- either... import Data.List intercalate "," lst -- or... import Data.List concat (intersperse "," lst)Splitting on a string
-- a.split(ss) -- You might need to get Data.List.Split from Cabal import Data.List.Split splitOn ss a -- using regexes import Text.Regex splitRegex (mkRegex ss) aDoes the string start with the prefix?
-- Python: a.startswith(b) import Data.List isPrefixOf b a -- ByteString import Data.ByteString isPrefixOf b aDoes the string end with the suffix?
-- Python: a.endswith(b) import Data.List isSuffixOf b a -- ByteString import Data.ByteString isSuffixOf b aDoes one string contain another?
-- Python: a.find(b) != -1 import Data.List isInfixOf b a -- ByteString import Data.ByteString isInfixOf b a -- ByteString import Data.ByteString findSubstring b a -- returns Just int or NothingReverse a string
-- Python: a[::-1] reverse a -- ByteString import Data.ByteString reverse bsAccess one character
-- Python: a[pos] a !! pos -- slow O(n) -- ByteString import Data.ByteString index a posWhere does one string contain another?
-- Python: a.find(b) import Data.ByteString findSubstring a bReplace substrings
-- Python: b = a.replace(src,dest) import Text.Regex b = subRegex (mkRegex src) a destReplace regex, calling function on substitution
-- Python: b = re.sub("[0-9]+", lambda x: str(int(x.group(0)) + 1), a) import Text.Regex (matchRegexAll, mkRegex) subRegexFn fn re s = concat $ reverse $ sub s [] where sub s accum = case matchRegexAll re s of Nothing -> s:accum Just (pre, mid, post, _) -> sub post $ (fn mid):pre:accum b = subRegexFn (read . (+ 1) . show) "[0-9]+" aStrip leading/trailing spaces
-- Python: a.strip() import Data.Char (isSpace) trim :: String -> String trim = f . f where f = reverse . dropWhile isSpaceLoop through every line in stdin
-- Python: loop through every line in stdin, applying a function -- for line in sys.stdin: -- print fn(line) let main = interact (unlines . map fn . lines) -- or... let main = do { a <- stdin; mapM_ print (map fn (lines a)); }Comments are moderated whenever I remember that I have a blog.
There are no comments on this article.