1
2
3
4
5
6 """This provides useful general functions for working with strings.
7
8 Functions:
9 splitany Split a string using many delimiters.
10 find_anychar Find one of a list of characters in a string.
11 rfind_anychar Find one of a list of characters in a string, from end to start.
12 starts_with Check whether a string starts with another string.
13
14 """
15 -def splitany(s, sep=" \011\012\013\014\015", maxsplit=None, negate=0):
16 """splitany(s [,sep [,maxsplit [,negate]]]) -> list of strings
17
18 Split a string. Similar to string.split, except that this considers
19 any one of the characters in sep to be a delimiter. If negate is
20 true, then everything but sep will be a separator.
21
22 """
23 strlist = []
24 prev = 0
25 for i in range(len(s)):
26 if maxsplit is not None and len(strlist) >= maxsplit:
27 break
28 if (s[i] in sep) == (not negate):
29 strlist.append(s[prev:i])
30 prev = i+1
31 strlist.append(s[prev:])
32 return strlist
33
35 """find_anychar(string, chars[, index]) -> index of a character or -1
36
37 Find a character in string. chars is a list of characters to look
38 for. Return the index of the first occurrence of any of the
39 characters, or -1 if not found. index is the index where the
40 search should start. By default, I search from the beginning of
41 the string.
42
43 """
44 if index is None:
45 index = 0
46 while index < len(string) and \
47 ((not negate and string[index] not in chars) or
48 (negate and string[index] in chars)):
49 index += 1
50 if index == len(string):
51 return -1
52 return index
53
55 """rfind_anychar(string, chars[, index]) -> index of a character or -1
56
57 Find a character in string, looking from the end to the start.
58 chars is a list of characters to look for. Return the index of
59 the first occurrence of any of the characters, or -1 if not found.
60 index is the index where the search should start. By default, I
61 search from the end of the string.
62
63 """
64 if index is None:
65 index = len(string)-1
66 while index >= 0 and \
67 ((not negate and string[index] not in chars) or
68 (negate and string[index] in chars)):
69 index -= 1
70
71 return index
72
73
75 """starts_with(s, start) -> 1/0
76
77 Return whether s begins with start.
78
79 """
80 return s[:len(start)] == start
81
82
83
84 try:
85 from cstringfns import *
86 except ImportError:
87 pass
88