query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
positions of substrings in string
|
python
|
def _string_substr(self, start, length=None):
"""
Pull substrings out of each string value by position and maximum
length.
Parameters
----------
start : int
First character to start splitting, indices starting at 0 (like
Python)
length : int, optional
Maximum length of each substring. If not supplied, splits each string
to the end
Returns
-------
substrings : type of caller
"""
op = ops.Substring(self, start, length)
return op.to_expr()
|
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/api.py#L1943-L1962
|
positions of substrings in string
|
python
|
def substrings(iterable):
"""Yield all of the substrings of *iterable*.
>>> [''.join(s) for s in substrings('more')]
['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more']
Note that non-string iterables can also be subdivided.
>>> list(substrings([0, 1, 2]))
[(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)]
"""
# The length-1 substrings
seq = []
for item in iter(iterable):
seq.append(item)
yield (item,)
seq = tuple(seq)
item_count = len(seq)
# And the rest
for n in range(2, item_count + 1):
for i in range(item_count - n + 1):
yield seq[i:i + n]
|
https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L689-L712
|
positions of substrings in string
|
python
|
def substrings_indexes(seq, reverse=False):
"""Yield all substrings and their positions in *seq*
The items yielded will be a tuple of the form ``(substr, i, j)``, where
``substr == seq[i:j]``.
This function only works for iterables that support slicing, such as
``str`` objects.
>>> for item in substrings_indexes('more'):
... print(item)
('m', 0, 1)
('o', 1, 2)
('r', 2, 3)
('e', 3, 4)
('mo', 0, 2)
('or', 1, 3)
('re', 2, 4)
('mor', 0, 3)
('ore', 1, 4)
('more', 0, 4)
Set *reverse* to ``True`` to yield the same items in the opposite order.
"""
r = range(1, len(seq) + 1)
if reverse:
r = reversed(r)
return (
(seq[i:i + L], i, i + L) for L in r for i in range(len(seq) - L + 1)
)
|
https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L715-L746
|
positions of substrings in string
|
python
|
def all_substrings(s):
''' yields all substrings of a string '''
join = ''.join
for i in range(1, len(s) + 1):
for sub in window(s, i):
yield join(sub)
|
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/all_substrings.py#L12-L17
|
positions of substrings in string
|
python
|
def str_slice(x, start=0, stop=None): # TODO: support n
"""Slice substrings from each string element in a column.
:param int start: The start position for the slice operation.
:param int end: The stop position for the slice operation.
:returns: an expression containing the sliced substrings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.slice(start=2, stop=5)
Expression = str_pandas_slice(text, start=2, stop=5)
Length: 5 dtype: str (expression)
---------------------------------
0 met
1 ry
2 co
3 r
4 y.
"""
if stop is None:
sll = _to_string_sequence(x).slice_string_end(start)
else:
sll = _to_string_sequence(x).slice_string(start, stop)
return sll
|
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/functions.py#L1290-L1324
|
positions of substrings in string
|
python
|
def __sub(self, string: str = '') -> str:
"""Replace spaces in string.
:param string: String.
:return: String without spaces.
"""
replacer = self.random.choice(['_', '-'])
return re.sub(r'\s+', replacer, string.strip())
|
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/file.py#L33-L40
|
positions of substrings in string
|
python
|
def _substitute(self, str):
"""
Substitute words in the string, according to the specified reflections,
e.g. "I'm" -> "you are"
:type str: str
:param str: The string to be mapped
:rtype: str
"""
if not self.attr.get("substitute",True):return str
return self._regex.sub(lambda mo:
self._reflections[mo.string[mo.start():mo.end()]],
str.lower())
|
https://github.com/ahmadfaizalbh/Chatbot/blob/5f886076f5116092226f61fc80264faa345b9839/chatbot/__init__.py#L419-L431
|
positions of substrings in string
|
python
|
def pipe_substr(context=None, _INPUT=None, conf=None, **kwargs):
"""A string module that returns a substring. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : iterable of items or strings
conf : {
'from': {'type': 'number', value': <starting position>},
'length': {'type': 'number', 'value': <count of characters to return>}
}
Returns
-------
_OUTPUT : generator of substrings
"""
conf['start'] = conf.pop('from', dict.get(conf, 'start'))
splits = get_splits(_INPUT, conf, **cdicts(opts, kwargs))
parsed = utils.dispatch(splits, *get_dispatch_funcs())
_OUTPUT = starmap(parse_result, parsed)
return _OUTPUT
|
https://github.com/ggaughan/pipe2py/blob/4767d6d1fd354d2a35e6528594b8deb8a033eed4/pipe2py/modules/pipesubstr.py#L55-L75
|
positions of substrings in string
|
python
|
def string(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default='', # type: Optional[Text]
omit_empty=False, # type: bool
strip_whitespace=True, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> Processor
"""
Create a processor for string values.
:param strip_whitespace: Indicates whether leading and trailing whitespace should be stripped
from parsed string values.
See also :func:`declxml.boolean`
"""
value_parser = _string_parser(strip_whitespace)
return _PrimitiveValue(
element_name,
value_parser,
attribute,
required,
alias,
default,
omit_empty,
hooks
)
|
https://github.com/gatkin/declxml/blob/3a2324b43aee943e82a04587fbb68932c6f392ba/declxml.py#L579-L608
|
positions of substrings in string
|
python
|
def p_string_expr_lp(p):
""" string : LP expr RP substr
"""
if p[2].type_ != TYPE.string:
syntax_error(p.lexer.lineno,
"Expected a string type expression. "
"Got %s type instead" % TYPE.to_string(p[2].type_))
p[0] = None
else:
p[0] = make_strslice(p.lexer.lineno, p[2], p[4][0], p[4][1])
|
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L2445-L2454
|
positions of substrings in string
|
python
|
def build_strings(strings, prefix):
"""Construct string definitions according to
the previously maintained table.
"""
strings = [
(
make_c_str(prefix + str(number), value),
reloc_ptr(
prefix + str(number), 'reloc_delta', 'char *'
)
) for value, number in sort_values(strings)
]
return [i[0] for i in strings], [i[1] for i in strings]
|
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/transformers.py#L180-L192
|
positions of substrings in string
|
python
|
def string_position(self, id_):
"""Returns a np array with indices to id_ (int) occurrences"""
if self.bow:
return self.string_start[self.positions[id_]]
else:
return self.string_start[[self.positions[id_]]]
|
https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L155-L160
|
positions of substrings in string
|
python
|
def apply_string_substitutions(
inputs,
substitutions,
inverse=False,
case_insensitive=False,
unused_substitutions="ignore",
):
"""Apply a number of substitutions to a string(s).
The substitutions are applied effectively all at once. This means that conflicting
substitutions don't interact. Where substitutions are conflicting, the one which
is longer takes precedance. This is confusing so we recommend that you look at
the examples.
Parameters
----------
inputs : str, list of str
The string(s) to which we want to apply the substitutions.
substitutions : dict
The substitutions we wish to make. The keys are the strings we wish to
substitute, the values are the strings which we want to appear in the output
strings.
inverse : bool
If True, do the substitutions the other way around i.e. use the keys as the
strings we want to appear in the output strings and the values as the strings
we wish to substitute.
case_insensitive : bool
If True, the substitutions will be made in a case insensitive way.
unused_substitutions : {"ignore", "warn", "raise"}, default ignore
Behaviour when one or more of the inputs does not have a corresponding
substitution. If "ignore", nothing happens. If "warn", a warning is issued. If
"raise", an error is raised. See the examples.
Returns
-------
``type(input)``
The input with substitutions performed.
Examples
--------
>>> apply_string_substitutions("Hello JimBob", {"Jim": "Bob"})
'Hello BobBob'
>>> apply_string_substitutions("Hello JimBob", {"Jim": "Bob"}, inverse=True)
'Hello JimJim'
>>> apply_string_substitutions(["Hello JimBob", "Jim says, 'Hi Bob'"], {"Jim": "Bob"})
['Hello BobBob', "Bob says, 'Hi Bob'"]
>>> apply_string_substitutions(["Hello JimBob", "Jim says, 'Hi Bob'"], {"Jim": "Bob"}, inverse=True)
['Hello JimJim', "Jim says, 'Hi Jim'"]
>>> apply_string_substitutions("Muttons Butter", {"M": "B", "Button": "Zip"})
'Buttons Butter'
# Substitutions don't cascade. If they did, Muttons would become Buttons, then the
# substitutions "Button" --> "Zip" would be applied and we would end up with
# "Zips Butter".
>>> apply_string_substitutions("Muttons Butter", {"Mutton": "Gutter", "tt": "zz"})
'Gutters Buzzer'
# Longer substitutions take precedent. Hence Mutton becomes Gutter, not Muzzon.
>>> apply_string_substitutions("Butter", {"buTTer": "Gutter"}, case_insensitive=True)
'Gutter'
>>> apply_string_substitutions("Butter", {"teeth": "tooth"})
'Butter'
>>> apply_string_substitutions("Butter", {"teeth": "tooth"}, unused_substitutions="ignore")
'Butter'
>>> apply_string_substitutions("Butter", {"teeth": "tooth"}, unused_substitutions="warn")
...pymagicc/utils.py:50: UserWarning: No substitution available for {'Butter'} warnings.warn(msg)
'Butter'
>>> apply_string_substitutions("Butter", {"teeth": "tooth"}, unused_substitutions="raise")
ValueError: No substitution available for {'Butter'}
"""
if inverse:
substitutions = {v: k for k, v in substitutions.items()}
# only possible to have conflicting substitutions when case insensitive
if case_insensitive:
_check_duplicate_substitutions(substitutions)
if unused_substitutions != "ignore":
_check_unused_substitutions(
substitutions, inputs, unused_substitutions, case_insensitive
)
compiled_regexp = _compile_replacement_regexp(
substitutions, case_insensitive=case_insensitive
)
inputs_return = deepcopy(inputs)
if isinstance(inputs_return, str):
inputs_return = _multiple_replace(inputs_return, substitutions, compiled_regexp)
else:
inputs_return = [
_multiple_replace(v, substitutions, compiled_regexp) for v in inputs_return
]
return inputs_return
|
https://github.com/openclimatedata/pymagicc/blob/d896014832cf458d1e95e5878fd6d5961f3e2e05/pymagicc/utils.py#L82-L188
|
positions of substrings in string
|
python
|
def itersplit(s, sep=None):
"""
Split a string by ``sep`` and yield chunks
Args:
s (str-type): string to split
sep (str-type): delimiter to split by
Yields:
generator of strings: chunks of string s
"""
if not s:
yield s
return
exp = re.compile(r'\s+' if sep is None else re.escape(sep))
pos = 0
while True:
m = exp.search(s, pos)
if not m:
if pos < len(s) or sep is not None:
yield s[pos:]
break
if pos < m.start() or sep is not None:
yield s[pos:m.start()]
pos = m.end()
|
https://github.com/westurner/pyrpo/blob/2a910af055dc405b761571a52ef87842397ddadf/pyrpo/pyrpo.py#L77-L101
|
positions of substrings in string
|
python
|
def strings_to_list_string(strings):
'''Takes a list of strings presumably containing words and phrases,
and returns a "list" form of those strings, like:
>>> strings_to_list_string(('cats', 'dogs'))
>>> 'cats and dogs'
or
>>> strings_to_list_string(('pizza', 'pop', 'chips'))
>>> 'pizza, pop, and chips'
Raises ValueError if strings is empty.
'''
if isinstance(strings, six.string_types):
raise TypeError('strings must be an iterable of strings, not a string '
'itself')
if len(strings) == 0:
raise ValueError('strings may not be empty')
elif len(strings) == 1:
return strings[0]
elif len(strings) == 2:
return ' and '.join(strings)
else:
return '{0}, and {1}'.format(', '.join(strings[:-1]),
strings[-1])
|
https://github.com/atmos-python/atmos/blob/f4af8eaca23cce881bde979599d15d322fc1935e/atmos/util.py#L66-L91
|
positions of substrings in string
|
python
|
def sub(self, repl, string, count=0):
"""Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl."""
return self._subx(repl, string, count, False)
|
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L144-L147
|
positions of substrings in string
|
python
|
def sort_string_by_pairs(strings):
"""Group a list of strings by pairs, by matching those with only
one character difference between each other together."""
assert len(strings) % 2 == 0
pairs = []
strings = list(strings) # This shallow copies the list
while strings:
template = strings.pop()
for i, candidate in enumerate(strings):
if count_string_diff(template, candidate) == 1:
pair = [template, strings.pop(i)]
pair.sort()
pairs.append(pair)
break
return pairs
|
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L120-L134
|
positions of substrings in string
|
python
|
def _slice(expr, start=None, stop=None, step=None):
"""
Slice substrings from each element in the sequence or scalar
:param expr:
:param start: int or None
:param stop: int or None
:param step: int or None
:return: sliced
"""
return _string_op(expr, Slice, _start=start, _end=stop, _step=step)
|
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/strings.py#L612-L623
|
positions of substrings in string
|
python
|
def str_slice(arr, start=None, stop=None, step=None):
"""
Slice substrings from each element in the Series or Index.
Parameters
----------
start : int, optional
Start position for slice operation.
stop : int, optional
Stop position for slice operation.
step : int, optional
Step size for slice operation.
Returns
-------
Series or Index of object
Series or Index from sliced substring from original string object.
See Also
--------
Series.str.slice_replace : Replace a slice with a string.
Series.str.get : Return element at position.
Equivalent to `Series.str.slice(start=i, stop=i+1)` with `i`
being the position.
Examples
--------
>>> s = pd.Series(["koala", "fox", "chameleon"])
>>> s
0 koala
1 fox
2 chameleon
dtype: object
>>> s.str.slice(start=1)
0 oala
1 ox
2 hameleon
dtype: object
>>> s.str.slice(stop=2)
0 ko
1 fo
2 ch
dtype: object
>>> s.str.slice(step=2)
0 kaa
1 fx
2 caeen
dtype: object
>>> s.str.slice(start=0, stop=5, step=3)
0 kl
1 f
2 cm
dtype: object
Equivalent behaviour to:
>>> s.str[0:5:3]
0 kl
1 f
2 cm
dtype: object
"""
obj = slice(start, stop, step)
f = lambda x: x[obj]
return _na_map(f, arr)
|
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/strings.py#L1345-L1413
|
positions of substrings in string
|
python
|
def p_subind_str(p):
""" substr : LP expr TO expr RP
"""
p[0] = (make_typecast(TYPE.uinteger, p[2], p.lineno(1)),
make_typecast(TYPE.uinteger, p[4], p.lineno(3)))
|
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L2457-L2461
|
positions of substrings in string
|
python
|
def split (s, delimter, trim = True, limit = 0): # pragma: no cover
"""
Split a string using a single-character delimter
@params:
`s`: the string
`delimter`: the single-character delimter
`trim`: whether to trim each part. Default: True
@examples:
```python
ret = split("'a,b',c", ",")
# ret == ["'a,b'", "c"]
# ',' inside quotes will be recognized.
```
@returns:
The list of substrings
"""
ret = []
special1 = ['(', ')', '[', ']', '{', '}']
special2 = ['\'', '"']
special3 = '\\'
flags1 = [0, 0, 0]
flags2 = [False, False]
flags3 = False
start = 0
nlim = 0
for i, c in enumerate(s):
if c == special3:
# next char is escaped
flags3 = not flags3
elif not flags3:
# no escape
if c in special1:
index = special1.index(c)
if index % 2 == 0:
flags1[int(index/2)] += 1
else:
flags1[int(index/2)] -= 1
elif c in special2:
index = special2.index(c)
flags2[index] = not flags2[index]
elif c == delimter and not any(flags1) and not any(flags2):
r = s[start:i]
if trim: r = r.strip()
ret.append(r)
start = i + 1
nlim = nlim + 1
if limit and nlim >= limit:
break
else:
# escaping closed
flags3 = False
r = s[start:]
if trim: r = r.strip()
ret.append(r)
return ret
|
https://github.com/pwwang/liquidpy/blob/f422af836740b7facfbc6b89e5162a17d619dd07/liquid/__init__.py#L367-L421
|
positions of substrings in string
|
python
|
def parse_string(self, string=''):
'''
Parse a string object to de-wikified text
'''
self.strings = string.splitlines(1)
self.strings = [self.__parse(line) for line in self.strings]
return ''.join(self.strings)
|
https://github.com/daddyd/dewiki/blob/84214bb9537326e036fa65e70d7a9ce7c6659c26/dewiki/parser.py#L45-L51
|
positions of substrings in string
|
python
|
def relevant_part(self, original, pos, sep=' '):
"""
calculates the subword in a `sep`-splitted list of substrings of
`original` that `pos` is ia.n
"""
start = original.rfind(sep, 0, pos) + 1
end = original.find(sep, pos - 1)
if end == -1:
end = len(original)
return original[start:end], start, end, pos - start
|
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/completion.py#L44-L53
|
positions of substrings in string
|
python
|
def findAllSubstrings(string, substring):
""" Returns a list of all substring starting positions in string or an empty
list if substring is not present in string.
:param string: a template string
:param substring: a string, which is looked for in the ``string`` parameter.
:returns: a list of substring starting positions in the template string
"""
#TODO: solve with regex? what about '.':
#return [m.start() for m in re.finditer('(?='+substring+')', string)]
start = 0
positions = []
while True:
start = string.find(substring, start)
if start == -1:
break
positions.append(start)
#+1 instead of +len(substring) to also find overlapping matches
start += 1
return positions
|
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/auxiliary.py#L471-L491
|
positions of substrings in string
|
python
|
def common_substring(s1, s2):
"""
Returns the longest common substring to the two strings, starting from the
left.
"""
chunks = []
path1 = splitall(s1)
path2 = splitall(s2)
for (dir1, dir2) in zip(path1, path2):
if dir1 != dir2:
break
chunks.append(dir1)
return os.path.join(*chunks)
|
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/past/translation/__init__.py#L190-L202
|
positions of substrings in string
|
python
|
def _string_to_substitute(self, mo, methods_dict):
"""
Return the string to be substituted for the match.
"""
matched_text, f_name = mo.groups()
# matched_text is the complete match string. e.g. plural_noun(cat)
# f_name is the function name. e.g. plural_noun
# Return matched_text if function name is not in methods_dict
if f_name not in methods_dict:
return matched_text
# Parse the matched text
a_tree = ast.parse(matched_text)
# get the args and kwargs from ast objects
args_list = [self._get_value_from_ast(a) for a in a_tree.body[0].value.args]
kwargs_list = {
kw.arg: self._get_value_from_ast(kw.value)
for kw in a_tree.body[0].value.keywords
}
# Call the corresponding function
return methods_dict[f_name](*args_list, **kwargs_list)
|
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2134-L2157
|
positions of substrings in string
|
python
|
def p_string_literal(self, p):
"""string_literal : STRING"""
p[0] = self.asttypes.String(p[1])
p[0].setpos(p)
|
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L230-L233
|
positions of substrings in string
|
python
|
def pos(self):
"""
Lazy-loads the part of speech tag for this word
:getter: Returns the plain string value of the POS tag for the word
:type: str
"""
if self._pos is None:
poses = self._element.xpath('POS/text()')
if len(poses) > 0:
self._pos = poses[0]
return self._pos
|
https://github.com/relwell/corenlp-xml-lib/blob/9b0f8c912ba3ecedd34473f74a9f2d033a75baf9/corenlp_xml/document.py#L416-L428
|
positions of substrings in string
|
python
|
def ipa_substrings(unicode_string, single_char_parsing=False):
"""
Return a list of (non-empty) substrings of the given string,
where each substring is either:
1. the longest Unicode string starting at the current index
representing a (known) valid IPA character, or
2. a single Unicode character (which is not IPA valid).
If ``single_char_parsing`` is ``False``,
parse the string one Unicode character at a time,
that is, do not perform the greedy parsing.
For example, if ``s = u"\u006e\u0361\u006d"``,
with ``single_char_parsing=True`` the result will be
a list with a single element: ``[u"\u006e\u0361\u006d"]``,
while ``single_char_parsing=False`` will yield a list with three elements:
``[u"\u006e", u"\u0361", u"\u006d"]``.
Return ``None`` if ``unicode_string`` is ``None``.
:param str unicode_string: the Unicode string to be parsed
:param bool single_char_parsing: if ``True``, parse one Unicode character at a time
:rtype: list of str
"""
return split_using_dictionary(
string=unicode_string,
dictionary=UNICODE_TO_IPA,
max_key_length=UNICODE_TO_IPA_MAX_KEY_LENGTH,
single_char_parsing=single_char_parsing
)
|
https://github.com/pettarin/ipapy/blob/ede4b3c40636f6eb90068369d31a2e75c7115324/ipapy/__init__.py#L72-L102
|
positions of substrings in string
|
python
|
def string(s):
'''Parser a string.'''
@Parser
def string_parser(text, index=0):
slen, tlen = len(s), len(text)
if text[index:index + slen] == s:
return Value.success(index + slen, s)
else:
matched = 0
while matched < slen and index + matched < tlen and text[index + matched] == s[matched]:
matched = matched + 1
return Value.failure(index + matched, s)
return string_parser
|
https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L638-L650
|
positions of substrings in string
|
python
|
def num_valid_substrings(self, path_to_words):
"""
For each string, find the count of all possible substrings with 2 characters or more that are contained in
the line-separated text file whose path is given.
:param str path_to_words: Path to file that contains a line-separated list of strings considered valid.
:returns: An H2OFrame with the number of substrings that are contained in the given word list.
"""
assert_is_type(path_to_words, str)
fr = H2OFrame._expr(expr=ExprNode("num_valid_substrings", self, path_to_words))
fr._ex._cache.nrows = self.nrow
fr._ex._cache.ncol = self.ncol
return fr
|
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/frame.py#L2461-L2473
|
positions of substrings in string
|
python
|
def pair_strings_sum_formatter(a, b):
"""
Formats the sum of a and b.
Note
----
Both inputs are numbers already converted to strings.
"""
if b[:1] == "-":
return "{0} - {1}".format(a, b[1:])
return "{0} + {1}".format(a, b)
|
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_text.py#L60-L71
|
positions of substrings in string
|
python
|
def iter_slices(string, slice_length):
"""Iterate over slices of a string."""
pos = 0
if slice_length is None or slice_length <= 0:
slice_length = len(string)
while pos < len(string):
yield string[pos:pos + slice_length]
pos += slice_length
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L514-L521
|
positions of substrings in string
|
python
|
def parse_substring(allele, pred, max_len=None):
"""
Extract substring of letters for which predicate is True
"""
result = ""
pos = 0
if max_len is None:
max_len = len(allele)
else:
max_len = min(max_len, len(allele))
while pos < max_len and pred(allele[pos]):
result += allele[pos]
pos += 1
return result, allele[pos:]
|
https://github.com/openvax/mhcnames/blob/71694b9d620db68ceee44da1b8422ff436f15bd3/mhcnames/parsing_helpers.py#L18-L31
|
positions of substrings in string
|
python
|
def split_strings(string, separators):
"""
Split a string with arbitrary number of separators.
Return a list with the splitted values
Arguments:
string (str): ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
results (list) : ex. ['a','1','2','b','2']
"""
logger = logging.getLogger('extract_vcf.split_strings')
logger.debug("splitting string '{0}' with separators {1}".format(
string, separators
))
results = []
def recursion(recursive_string, separators, i=1):
"""
Split a string with arbitrary number of separators.
Add the elements of the string to global list result.
Arguments:
string : ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
Adds splitted string to results. ex. ['a','1','2','b','2']
"""
if i == len(separators):
for value in recursive_string.split(separators[i-1]):
logger.debug("Adding {0} to results".format(value))
results.append(value)
else:
for value in recursive_string.split(separators[i-1]):
recursion(value, separators, i+1)
if len(separators) > 0:
recursion(string, separators)
else:
results = [string]
return results
|
https://github.com/moonso/extract_vcf/blob/c8381b362fa6734cd2ee65ef260738868d981aaf/extract_vcf/get_annotations.py#L6-L48
|
positions of substrings in string
|
python
|
def set_max_strings(self, max_strings):
"""stub"""
if not self.my_osid_object_form._is_valid_integer(
max_strings, self.get_max_strings_metadata()):
raise InvalidArgument('maxStrings')
self.my_osid_object_form._my_map['maxStrings'] = max_strings
|
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/qti/extended_text_interaction.py#L106-L111
|
positions of substrings in string
|
python
|
def as_fstring(text):
"""expansion with python f-string, usually ok, but with the case
of ' inside expressions, adding repr will add backslash to it
and cause trouble.
"""
for quote in ('"""', "'''"):
# although script-format always ends with \n, direct use of this function might
# have string ending with " or '
if quote not in text and not text.endswith(quote[0]):
return 'fr' + quote + text + quote
# now, we need to look into the structure of f-string
pieces = split_fstring(text)
# if all expressions do not have single quote, we can
# safely repr the entire string
if not any("'" in piece for piece in pieces[1::2]):
return 'f' + repr(text)
#
# unfortunately, this thing has both single and double triple quotes
# because we cannot use backslash inside expressions in f-string, we
# have to use format string now.
args = []
for idx in range(len(pieces))[1::2]:
pos = valid_expr_till(pieces[idx])
if pos == 0:
raise SyntaxError(f'invalid expression in {pieces[idx]}')
args.append(pieces[idx][:pos])
pieces[idx] = '{' + str(idx // 2) + pieces[idx][pos:] + '}'
return repr(''.join(pieces)) + '.format(' + ', '.join(args) + ')'
|
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/utils.py#L902-L930
|
positions of substrings in string
|
python
|
def isstring(self, string, *args):
"""Is string
args:
string (str): match
returns:
bool
"""
regex = re.compile(r'\'[^\']*\'|"[^"]*"')
return regex.match(string)
|
https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/plib/call.py#L145-L153
|
positions of substrings in string
|
python
|
def split_string_at_suffix(s, numbers_into_suffix=False):
"""
Split a string into two parts: a prefix and a suffix. Splitting is done from the end,
so the split is done around the position of the last digit in the string
(that means the prefix may include any character, mixing digits and chars).
The flag 'numbers_into_suffix' determines whether the suffix consists of digits or non-digits.
"""
if not s:
return (s, '')
pos = len(s)
while pos and numbers_into_suffix == s[pos-1].isdigit():
pos -= 1
return (s[:pos], s[pos:])
|
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/tablegenerator/util.py#L110-L122
|
positions of substrings in string
|
python
|
def pos(string, substr, start):
"""
Find the first occurrence in a string of a substring, starting at
a specified location, searching forward.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pos_c.html
:param string: Any character string.
:type string: str
:param substr: Substring to locate in the character string.
:type substr: str
:param start: Position to begin looking for substr in string.
:type start: int
:return:
The index of the first occurrence of substr
in string at or following index start.
:rtype: int
"""
string = stypes.stringToCharP(string)
substr = stypes.stringToCharP(substr)
start = ctypes.c_int(start)
return libspice.pos_c(string, substr, start)
|
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L9793-L9814
|
positions of substrings in string
|
python
|
def compat_string(value):
"""
Provide a python2/3 compatible string representation of the value
:type value:
:rtype :
"""
if isinstance(value, bytes):
return value.decode(encoding='utf-8')
return str(value)
|
https://github.com/cablehead/python-consul/blob/53eb41c4760b983aec878ef73e72c11e0af501bb/consul/twisted.py#L54-L62
|
positions of substrings in string
|
python
|
def _splitstrip(string, sep=","):
"""return a list of stripped string by splitting the string given as
argument on `sep` (',' by default). Empty string are discarded.
>>> _splitstrip('a, b, c , 4,,')
['a', 'b', 'c', '4']
>>> _splitstrip('a')
['a']
>>> _splitstrip('a,\nb,\nc,')
['a', 'b', 'c']
:type string: str or unicode
:param string: a csv line
:type sep: str or unicode
:param sep: field separator, default to the comma (',')
:rtype: str or unicode
:return: the unquoted string (or the input string if it wasn't quoted)
"""
return [word.strip() for word in string.split(sep) if word.strip()]
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/utils/utils.py#L258-L278
|
positions of substrings in string
|
python
|
def sub(self, replace, string, count=0):
""" returns new string where the matching cases (limited by the count) in
the string is replaced. """
return self.re.sub(replace, string, count)
|
https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/utility.py#L186-L189
|
positions of substrings in string
|
python
|
def is_string(obj):
"""Is this a string.
:param object obj:
:rtype: bool
"""
if PYTHON3:
str_type = (bytes, str)
else:
str_type = (bytes, str, unicode)
return isinstance(obj, str_type)
|
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/compatibility.py#L74-L84
|
positions of substrings in string
|
python
|
def p_string_list(self, t):
"""string_list : string_list COMMA STRING
| STRING
| empty"""
if len(t) == 4:
t[0] = t[1]
t[0].append(t[3])
elif t[1]:
t[0] = [t[1]]
else:
t[0] = []
|
https://github.com/grycap/RADL/blob/03ccabb0313a48a5aa0e20c1f7983fddcb95e9cb/radl/radl_parse.py#L340-L351
|
positions of substrings in string
|
python
|
def SplitString(value):
"""simple method that puts in spaces every 10 characters"""
string_length = len(value)
chunks = int(string_length / 10)
string_list = list(value)
lstring = ""
if chunks > 1:
lstring = "\\markup { \n\r \column { "
for i in range(int(chunks)):
lstring += "\n\r\r \\line { \""
index = i * 10
for i in range(index):
lstring += string_list[i]
lstring += "\" \r\r}"
lstring += "\n\r } \n }"
if lstring == "":
indexes = [
i for i in range(
len(string_list)) if string_list[i] == "\r" or string_list[i] == "\n"]
lstring = "\\markup { \n\r \column { "
if len(indexes) == 0:
lstring += "\n\r\r \\line { \"" + \
"".join(string_list) + "\" \n\r\r } \n\r } \n }"
else:
rows = []
row_1 = string_list[:indexes[0]]
rows.append(row_1)
for i in range(len(indexes)):
start = indexes[i]
if i != len(indexes) - 1:
end = indexes[i + 1]
else:
end = len(string_list)
row = string_list[start:end]
rows.append(row)
for row in rows:
lstring += "\n\r\r \\line { \""
lstring += "".join(row)
lstring += "\" \r\r}"
lstring += "\n\r } \n }"
return lstring
|
https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/helpers.py#L4-L46
|
positions of substrings in string
|
python
|
def strnum(prefix: str, num: int, suffix: str = "") -> str:
"""
Makes a string of the format ``<prefix><number><suffix>``.
"""
return "{}{}{}".format(prefix, num, suffix)
|
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L130-L134
|
positions of substrings in string
|
python
|
def append_strings(self, string_list, header=False):
"""Append tag=pairs for each supplied string.
:param string_list: List of "tag=value" strings.
:param header: Append to header if True; default to body.
Each string is split, and the resulting tag and value strings
are appended to the message."""
for s in string_list:
self.append_string(s, header=header)
return
|
https://github.com/da4089/simplefix/blob/10f7f165a99a03467110bee69cc7c083c3531c68/simplefix/message.py#L462-L473
|
positions of substrings in string
|
python
|
def _compare_strings(cls, source, target):
"""
Compares a source string to a target string,
and addresses the condition in which the source string
includes unquoted special characters.
It performs a simple regular expression match,
with the assumption that (as required) unquoted special characters
appear only at the beginning and/or the end of the source string.
It also properly differentiates between unquoted and quoted
special characters.
:param string source: First string value
:param string target: Second string value
:returns: The comparison relation among input strings.
:rtype: int
"""
start = 0
end = len(source)
begins = 0
ends = 0
# Reading of initial wildcard in source
if source.startswith(CPEComponent2_3_WFN.WILDCARD_MULTI):
# Source starts with "*"
start = 1
begins = -1
else:
while ((start < len(source)) and
source.startswith(CPEComponent2_3_WFN.WILDCARD_ONE,
start, start)):
# Source starts with one or more "?"
start += 1
begins += 1
# Reading of final wildcard in source
if (source.endswith(CPEComponent2_3_WFN.WILDCARD_MULTI) and
CPESet2_3._is_even_wildcards(source, end - 1)):
# Source ends in "*"
end -= 1
ends = -1
else:
while ((end > 0) and
source.endswith(CPEComponent2_3_WFN.WILDCARD_ONE, end - 1, end) and
CPESet2_3._is_even_wildcards(source, end - 1)):
# Source ends in "?"
end -= 1
ends += 1
source = source[start: end]
index = -1
leftover = len(target)
while (leftover > 0):
index = target.find(source, index + 1)
if (index == -1):
break
escapes = target.count("\\", 0, index)
if ((index > 0) and (begins != -1) and
(begins < (index - escapes))):
break
escapes = target.count("\\", index + 1, len(target))
leftover = len(target) - index - escapes - len(source)
if ((leftover > 0) and ((ends != -1) and (leftover > ends))):
continue
return CPESet2_3.LOGICAL_VALUE_SUPERSET
return CPESet2_3.LOGICAL_VALUE_DISJOINT
|
https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpeset2_3.py#L124-L198
|
positions of substrings in string
|
python
|
def p_subind_strTO(p):
""" substr : LP TO expr RP
"""
p[0] = (make_typecast(TYPE.uinteger, make_number(0, lineno=p.lineno(2)),
p.lineno(1)),
make_typecast(TYPE.uinteger, p[3], p.lineno(2)))
|
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L2464-L2469
|
positions of substrings in string
|
python
|
def format_strings(self, **kwargs):
"""String substitution of name."""
return mutablerecords.CopyRecord(
self, name=util.format_string(self.name, kwargs))
|
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L96-L99
|
positions of substrings in string
|
python
|
def _split(string, splitters):
"""Splits a string into parts at multiple characters"""
part = ''
for character in string:
if character in splitters:
yield part
part = ''
else:
part += character
yield part
|
https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L32-L41
|
positions of substrings in string
|
python
|
def to_string(self):
"""
stringifies version
:return: string of version
"""
if self.major == -1:
major_str = 'x'
else:
major_str = self.major
if self.minor == -1:
minor_str = 'x'
else:
minor_str = self.minor
if self.patch == -1:
patch_str = 'x'
else:
patch_str = self.patch
return '{0}_{1}_{2}'.format(major_str, minor_str, patch_str)
|
https://github.com/sparknetworks/pgpm/blob/1a060df46a886095181f692ea870a73a32510a2e/pgpm/lib/utils/config.py#L180-L197
|
positions of substrings in string
|
python
|
def _strslices(self):
"""Stringify slices list (x-y/step format)"""
pad = self.padding or 0
for sli in self.slices():
if sli.start + 1 == sli.stop:
yield "%0*d" % (pad, sli.start)
else:
assert sli.step >= 0, "Internal error: sli.step < 0"
if sli.step == 1:
yield "%0*d-%0*d" % (pad, sli.start, pad, sli.stop - 1)
else:
yield "%0*d-%0*d/%d" % (pad, sli.start, pad, sli.stop - 1, \
sli.step)
|
https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/ClusterShell/RangeSet.py#L271-L283
|
positions of substrings in string
|
python
|
def string_to_basename(s):
'''
Converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
'''
s = s.strip().lower()
s = re.sub(r'[^\w\s-]', '', s)
return re.sub(r'[\s-]+', '-', s)
|
https://github.com/Nagasaki45/bibo/blob/e6afb28711e78eb11475834d3f9455252ac9f347/bibo/internals.py#L90-L97
|
positions of substrings in string
|
python
|
def to_string(self):
"""Return a string that tries to reconstitute the variable decl."""
suffix = '%s %s' % (self.type, self.name)
if self.initial_value:
suffix += ' = ' + self.initial_value
return suffix
|
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/ast.py#L201-L206
|
positions of substrings in string
|
python
|
def decode(s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
strs = []
i = 0
while i < len(s):
index = s.find(":", i)
size = int(s[i:index])
strs.append(s[index+1: index+1+size])
i = index+1+size
return strs
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/encode_decode.py#L18-L30
|
positions of substrings in string
|
python
|
def to_string_short(self):
"""
see also :meth:`to_string`
:return: a shorter abreviated string reprentation of the parameter
"""
opt = np.get_printoptions()
np.set_printoptions(threshold=8, edgeitems=3, linewidth=opt['linewidth']-len(self.uniquetwig)-2)
str_ = super(FloatArrayParameter, self).to_string_short()
np.set_printoptions(**opt)
return str_
|
https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4596-L4606
|
positions of substrings in string
|
python
|
def to_compressed_string(val, max_length=0):
"""Converts val to a compressed string.
A compressed string is one with no leading or trailing spaces.
If val is None, or is blank (all spaces) None is returned.
If max_length > 0 and the stripped val is greater than max_length, val[:max_length] is returned.
"""
if val is None or len(val) == 0:
return None
rval = " ".join(val.split())
if len(rval) == 0:
return None
if max_length == 0:
return rval
else:
return rval[:max_length]
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/convert.py#L55-L72
|
positions of substrings in string
|
python
|
def as_posix(self):
"""Return the string representation of the path with forward (/)
slashes."""
f = self._flavour
return str(self).replace(f.sep, '/')
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L896-L900
|
positions of substrings in string
|
python
|
def __str(self, quote=False, sep=" ", prefix="", suffix=""):
"""Format a SoSOptions object as a human or machine readable string.
:param quote: quote option values
:param sep: list separator string
:param prefix: arbitrary prefix string
:param suffix: arbitrary suffix string
:param literal: print values as Python literals
"""
args = prefix
arg_fmt = "=%s"
for arg in _arg_names:
args += arg + arg_fmt + sep
args.strip(sep)
vals = [getattr(self, arg) for arg in _arg_names]
if not quote:
# Convert Python source notation for sequences into plain strings
vals = [",".join(v) if _is_seq(v) else v for v in vals]
else:
def is_string(val):
return isinstance(val, six.string_types)
# Only quote strings if quote=False
vals = ["'%s'" % v if is_string(v) else v for v in vals]
return (args % tuple(vals)).strip(sep) + suffix
|
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L111-L136
|
positions of substrings in string
|
python
|
def strings_to_(strings: Iterable[str], f: Callable) -> Iterable[Any]:
"""
Convert a list of strings to a list of certain form, specified by *f*.
:param strings: a list of string
:param f: a function that converts your string
:return: type undefined, but specified by `to_type`
.. doctest::
>>> strings_to_(['0.333', '0.667', '0.250'], float)
[0.333, 0.667, 0.25]
"""
if not all_string_like(strings):
raise TypeError('All have to be strings!')
# ``type(strs)`` is the container of *strs*.
return type(strings)(map(f, strings))
|
https://github.com/singularitti/scientific-string/blob/615dca747e8fb1e89ed1d9f18aef4066295a17a9/scientific_string/strings.py#L20-L36
|
positions of substrings in string
|
python
|
def python(string: str):
"""
:param string: String can be type, resource or python case
"""
return underscore(singularize(string) if Naming._pluralize(string) else string)
|
https://github.com/eReuse/utils/blob/989062e85095ea4e1204523fe0e298cf1046a01c/ereuse_utils/naming.py#L35-L39
|
positions of substrings in string
|
python
|
def substr(self, name, start=None, size=None):
"""
Return a substring of the string at key ``name``. ``start`` and ``size``
are 0-based integers specifying the portion of the string to return.
Like **Redis.SUBSTR**
:param string name: the key name
:param int start: Optional, the offset of first byte returned. If start
is negative, the returned string will start at the start'th character
from the end of string.
:param int size: Optional, number of bytes returned. If size is
negative, then that many characters will be omitted from the end of string.
:return: The extracted part of the string.
:rtype: string
>>> ssdb.set('str_test', 'abc12345678')
True
>>> ssdb.substr('str_test', 2, 4)
'c123'
>>> ssdb.substr('str_test', -2, 2)
'78'
>>> ssdb.substr('str_test', 1, -1)
'bc1234567'
"""
if start is not None and size is not None:
start = get_integer('start', start)
size = get_integer('size', size)
return self.execute_command('substr', name, start, size)
elif start is not None:
start = get_integer('start', start)
return self.execute_command('substr', name, start)
return self.execute_command('substr', name)
|
https://github.com/wrongwaycn/ssdb-py/blob/ce7b1542f0faa06fe71a60c667fe15992af0f621/ssdb/client.py#L559-L591
|
positions of substrings in string
|
python
|
def strip_string(self, string, *args):
"""Strips matching regular expressions from string
Keyword arguments:
string -- The given string, that will be stripped
*args -- List of regex strings, that are used in parsing
Returns:
String with *args removed from string
"""
res = string
for r in args:
res = re.sub(r, "", res.strip(),
flags=re.IGNORECASE|re.MULTILINE)
return res.strip()
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L112-L126
|
positions of substrings in string
|
python
|
def StrSubstr(start_idx, count, initial_string):
"""
Create a concrete version of the substring
:param start_idx : starting index of the substring
:param end_idx : last index of the substring
:param initial_string
:return : a concrete version of the substring
"""
new_value = initial_string.value[start_idx.value:start_idx.value + count.value]
return StringV(new_value)
|
https://github.com/angr/claripy/blob/4ed61924880af1ea8fb778047d896ec0156412a6/claripy/strings.py#L22-L32
|
positions of substrings in string
|
python
|
def _transpose_chars(text, pos):
"""
Drag the character before pos forward over the character at pos,
moving pos forward as well. If pos is at the end of text, then this
transposes the two characters before pos.
"""
if len(text) < 2 or pos == 0:
return text, pos
if pos == len(text):
return text[:pos - 2] + text[pos - 1] + text[pos - 2], pos
return text[:pos - 1] + text[pos] + text[pos - 1] + text[pos + 1:], pos + 1
|
https://github.com/jangler/readlike/blob/2901260c50bd1aecfb981c3990e0c6333de8aac8/readlike.py#L153-L163
|
positions of substrings in string
|
python
|
def str_title(x):
"""Converts all string samples to titlecase.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.title()
Expression = str_title(text)
Length: 5 dtype: str (expression)
---------------------------------
0 Something
1 Very Pretty
2 Is Coming
3 Our
4 Way.
"""
sl = _to_string_sequence(x).title()
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)
|
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/functions.py#L1412-L1441
|
positions of substrings in string
|
python
|
def split(pattern, string, maxsplit=0, flags=0):
"""Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings."""
return _compile(pattern, flags).split(string, maxsplit)
|
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/re.py#L171-L174
|
positions of substrings in string
|
python
|
def _str_sid(self):
'Return a nicely formatted representation string'
sub_auths = "-".join([str(sub) for sub in self.sub_authorities])
return f'S-{self.revision_number}-{self.authority}-{sub_auths}'
|
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/attribute.py#L1982-L1985
|
positions of substrings in string
|
python
|
def parse_string(cls, content, basedir=None, resolve=True, unresolved_value=DEFAULT_SUBSTITUTION):
"""Parse URL
:param content: content to parse
:type content: basestring
:param resolve: If true, resolve substitutions
:param resolve: if true, resolve substitutions
:type resolve: boolean
:param unresolved_value: assigned value value to unresolved substitution.
If overriden with a default value, it will replace all unresolved value to the default value.
If it is set to to pyhocon.STR_SUBSTITUTION then it will replace the value by its substitution expression (e.g., ${x})
:type unresolved_value: boolean
:return: Config object
:type return: Config
"""
return ConfigParser().parse(content, basedir, resolve, unresolved_value)
|
https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_parser.py#L135-L150
|
positions of substrings in string
|
python
|
def multisplit(s, seps=list(string.punctuation) + list(string.whitespace), blank=True):
r"""Just like str.split(), except that a variety (list) of seperators is allowed.
>>> multisplit(r'1-2?3,;.4+-', string.punctuation)
['1', '2', '3', '', '', '4', '', '']
>>> multisplit(r'1-2?3,;.4+-', string.punctuation, blank=False)
['1', '2', '3', '4']
>>> multisplit(r'1C 234567890', '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n' + string.punctuation)
['1C 234567890']
"""
seps = str().join(seps)
return [s2 for s2 in s.translate(str().join([(chr(i) if chr(i) not in seps else seps[0])
for i in range(256)])).split(seps[0]) if (blank or s2)]
|
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2188-L2200
|
positions of substrings in string
|
python
|
def subat(orig, index, replace):
"""Substitutes the replacement string/character at the given index in the
given string, returns the modified string.
**Examples**:
::
auxly.stringy.subat("bit", 2, "n")
"""
return "".join([(orig[x] if x != index else replace) for x in range(len(orig))])
|
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/stringy.py#L12-L20
|
positions of substrings in string
|
python
|
def indent_string(string, num_spaces=2):
'''Add indentation to a string.
Replaces all new lines in the string with a new line followed by the
specified number of spaces, and adds the specified number of spaces to the
start of the string.
'''
indent = ' '.ljust(num_spaces)
return indent + re.sub('\n', '\n' + indent, string)
|
https://github.com/gbiggs/rtsprofile/blob/fded6eddcb0b25fe9808b1b12336a4413ea00905/rtsprofile/utils.py#L72-L81
|
positions of substrings in string
|
python
|
def match(self, string, pos):
'''string is of course a py string'''
return self.pat.match(string, int(pos))
|
https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/internals/base.py#L577-L579
|
positions of substrings in string
|
python
|
def compile_string(string, compiler_class=Compiler, **kwargs):
"""Compile a single string, and return a string of CSS.
Keyword arguments are passed along to the underlying `Compiler`.
"""
compiler = compiler_class(**kwargs)
return compiler.compile_string(string)
|
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L240-L246
|
positions of substrings in string
|
python
|
def string(self) -> str:
"""Return str(self)."""
start, end = self._span
return self._lststr[0][start:end]
|
https://github.com/5j9/wikitextparser/blob/1347425814361d7955342c53212edbb27f0ff4b5/wikitextparser/_wikitext.py#L297-L300
|
positions of substrings in string
|
python
|
def string(self):
"""
Return the first string term in the conjunction, or `None`.
"""
for term in self._terms:
if isinstance(term, String):
return str(term)
return None
|
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tdl.py#L607-L614
|
positions of substrings in string
|
python
|
def valid_substitution(strlen, index):
"""
skip performing substitutions that are outside the bounds of the string
"""
values = index[0]
return all([strlen > i for i in values])
|
https://github.com/vals/umis/blob/e8adb8486d9e9134ab8a6cad9811a7e74dcc4a2c/umis/barcodes.py#L172-L177
|
positions of substrings in string
|
python
|
def splitany(s, sep=None, maxsplit=-1):
"""
Splits "s" into substrings using "sep" as the delimiter string. Behaves like str.split, except that:
1. Single strings are parsed into characters, any of which may be used as a delimiter
2. Lists or tuples of multiple character strings may be provided, and thus used as delimiters
If "sep" is None, a single character, or a list with one string, str.split is called directly.
Otherwise, "s" is parsed iteratively until all delimiters have been found, or maxsplit has been reached.
:param s: the unicode or binary string to split
:param sep: a string or list of strings to use as delimiter in the split (defaults to whitespace):
if a string, split on any char; if a list or tuple, split on any of its values
:param maxsplit: if provided, the maximum number of splits to perform
:return: the list of substrings in "s" between occurrences of "sep"
"""
if s is None:
return []
elif not isinstance(s, STRING_TYPES):
raise TypeError('Cannot split a {t}: {s}'.format(s=s, t=type(s).__name__))
elif sep is None:
return s.split(sep, maxsplit)
elif not isinstance(sep, _split_sep_types):
raise TypeError('Cannot split on a {t}: {s}'.format(s=sep, t=type(sep).__name__))
else:
split_on_any_char = isinstance(sep, STRING_TYPES)
if split_on_any_char:
# Python 3 compliance: sync and wrap to prevent issues with Binary: b'a'[0] == 97
seps = [_sync_string_to(s, sep)]
elif all(isinstance(sub, STRING_TYPES) for sub in sep):
# Python 3 compliance: sync, but also sort keys by length to do largest matches first
seps = [_sync_string_to(s, sub) for sub in sep]
else:
invalid_seps = [sub for sub in sep if not isinstance(sep, STRING_TYPES)]
raise TypeError('Cannot split on the following: {s}'.format(s=invalid_seps))
if len(s) == 0 or len(seps) == 0 or maxsplit == 0:
return [s]
elif len(seps) == 1:
# Reduce to single char or list item
# Call split if sep like: 'a', ['a'], ['ab']
# Otherwise, split on any if sep like: 'ab'
seps = seps[0]
if not split_on_any_char or len(seps) == 1:
return s.split(seps, maxsplit)
as_text = isinstance(seps, _split_txt_types)
parts = []
start = 0
rest = None
try:
while maxsplit < 0 or maxsplit >= len(parts):
rest = s if start == 0 else rest[start:]
# Sort based on (index_in_sep, negative_len_of_sep) to do largest matches first
if as_text:
stop = min((rest.index(sub), 0 - len(sub)) for sub in seps if sub in rest)
else:
# Python 3 compliance: iterating over bytes results in ints
stop = min((rest.index(sub), 0 - len(bytes([sub]))) for sub in seps if sub in rest)
parts.append(rest if maxsplit == len(parts) else rest[:stop[0]])
start = stop[0] - stop[1] # Skip full index of last delim
except ValueError:
parts.append(rest)
return parts
|
https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/strings.py#L120-L192
|
positions of substrings in string
|
python
|
def normalise_string(string):
""" Strips trailing whitespace from string, lowercases it and replaces
spaces with underscores
"""
string = (string.strip()).lower()
return re.sub(r'\W+', '_', string)
|
https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/seed_control_interface_service/utils.py#L6-L11
|
positions of substrings in string
|
python
|
def has_substring(self, substring):
"""
Construct a Filter matching values containing ``substring``.
Parameters
----------
substring : str
Sub-string against which to compare values produced by ``self``.
Returns
-------
matches : Filter
Filter returning True for all sid/date pairs for which ``self``
produces a string containing ``substring``.
"""
return ArrayPredicate(
term=self,
op=LabelArray.has_substring,
opargs=(substring,),
)
|
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/classifiers/classifier.py#L196-L215
|
positions of substrings in string
|
python
|
def parse(s):
r"""
Returns a list of strings or format dictionaries to describe the strings.
May raise a ValueError if it can't be parsed.
>>> parse(">>> []")
['>>> []']
>>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m")
"""
stuff = []
rest = s
while True:
front, token, rest = peel_off_esc_code(rest)
if front:
stuff.append(front)
if token:
try:
tok = token_type(token)
if tok:
stuff.extend(tok)
except ValueError:
raise ValueError("Can't parse escape sequence: %r %r %r %r" % (s, repr(front), token, repr(rest)))
if not rest:
break
return stuff
|
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/escseqparse.py#L23-L48
|
positions of substrings in string
|
python
|
def parseStringList(s):
"""
Parse a string of space-separated numbers, returning a Python list.
:param s: (string) to parse
:returns: (list) binary SDR
"""
assert isinstance(s, basestring)
return [int(i) for i in s.split()]
|
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/utils.py#L207-L215
|
positions of substrings in string
|
python
|
def split_str(string):
"""Split string in half to return two strings"""
split = string.split(' ')
return ' '.join(split[:len(split) // 2]), ' '.join(split[len(split) // 2:])
|
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/modify/draw/pdf.py#L25-L28
|
positions of substrings in string
|
python
|
def subst_quoted_strings(sql, params):
"""Reverse operation to mark_quoted_strings - substitutes '@' by params.
"""
parts = sql.split('@')
params_dont_match = "number of parameters doesn' match the transformed query"
assert len(parts) == len(params) + 1, params_dont_match # would be internal error
out = []
for i, param in enumerate(params):
out.append(parts[i])
out.append("'%s'" % param.replace('\\', '\\\\').replace("\'", "\\\'"))
out.append(parts[-1])
return ''.join(out)
|
https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/dbapi/subselect.py#L217-L228
|
positions of substrings in string
|
python
|
def paren_split(sep,string):
"""
Splits the string into pieces divided by sep, when sep is outside of parentheses.
"""
if len(sep) != 1: raise Exception("Separation string must be one character long")
retlist = []
level = 0
blevel = 0
left = 0
for i in range(len(string)):
if string[i] == "(": level += 1
elif string[i] == ")": level -= 1
elif string[i] == "[": blevel += 1
elif string[i] == "]": blevel -= 1
elif string[i] == sep and level == 0 and blevel == 0:
retlist.append(string[left:i])
left = i+1
retlist.append(string[left:])
return retlist
|
https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/utils.py#L88-L106
|
positions of substrings in string
|
python
|
def parse(v):
"""
Parse a slice string, of the same form as used by __getitem__
>>> Slice.parse("2:3,7,10:12")
:param v: Input string
:return: A list of tuples, one for each element of the slice string
"""
parts = v.split(',')
slices = []
for part in parts:
p = part.split(':')
if len(p) == 1:
slices.append(int(p[0]))
elif len(p) == 2:
slices.append(tuple(p))
else:
raise ValueError("Too many ':': {}".format(part))
return slices
|
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/etl/pipeline.py#L596-L620
|
positions of substrings in string
|
python
|
def tostring(self, encoding):
""" quote the string if not encoded
else encode and return """
if self.kind == 'string':
if encoding is not None:
return self.converted
return '"{converted}"'.format(converted=self.converted)
elif self.kind == 'float':
# python 2 str(float) is not always
# round-trippable so use repr()
return repr(self.converted)
return self.converted
|
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/computation/pytables.py#L584-L595
|
positions of substrings in string
|
python
|
def rest_of_string(self, offset=0):
"""A copy of the current position till the end of the source string."""
if self.has_space(offset=offset):
return self.string[self.pos + offset:]
else:
return ''
|
https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/partpy/sourcestring.py#L188-L193
|
positions of substrings in string
|
python
|
def to_string(self, verbose=0):
"""String representation."""
rows = [[it + 1] + list(map(str, (self[k][it] for k in self.keys())))
for it in range(self.num_iterations)]
return tabulate(rows, headers=["Iter"] + list(self.keys()))
|
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/abiinspect.py#L137-L142
|
positions of substrings in string
|
python
|
def string(self, *pattern, **kwargs):
"""
Add string pattern
:param pattern:
:type pattern:
:return: self
:rtype: Rebulk
"""
self.pattern(self.build_string(*pattern, **kwargs))
return self
|
https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/rebulk.py#L146-L156
|
positions of substrings in string
|
python
|
def set_string(self, string):
"""Set the working string and its length then reset positions."""
self.string = string
self.length = len(string)
self.reset_position()
|
https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/partpy/sourcestring.py#L38-L42
|
positions of substrings in string
|
python
|
def fmt_subst(regex, subst):
"""Replace regex with string."""
return lambda text: re.sub(regex, subst, text) if text else text
|
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L89-L91
|
positions of substrings in string
|
python
|
def split(s, posix=True):
"""Split the string s using shell-like syntax.
Args:
s (str): String to split
posix (bool): Use posix split
Returns:
list of str: List of string parts
"""
if isinstance(s, six.binary_type):
s = s.decode("utf-8")
return shlex.split(s, posix=posix)
|
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L25-L37
|
positions of substrings in string
|
python
|
def get_strings(self, need_quote=False):
"""ret: string"""
self.skip()
if self.buf[0] == ';' or self.buf[0] == '{' or self.buf[0] == '}':
error.err_add(self.errors, self.pos,
'EXPECTED_ARGUMENT', self.buf[0])
raise error.Abort
if self.buf[0] == '"' or self.buf[0] == "'":
# for double-quoted string, loop over string and translate
# escaped characters. also strip leading whitespace as
# necessary.
# for single-quoted string, keep going until end quote is found.
quote_char = self.buf[0]
# collect output in strs (list of strings)
strs = []
res = []
# remember position of " character
indentpos = self.offset
i = 1
while True:
buflen = len(self.buf)
start = i
while i < buflen:
if self.buf[i] == quote_char:
# end-of-string; copy the buf to output
res.append(self.buf[start:i])
strs.append((u''.join(res), quote_char))
# and trim buf
self.set_buf(i+1)
# check for '+' operator
self.skip()
if self.buf[0] == '+':
self.set_buf(1)
self.skip()
nstrs = self.get_strings(need_quote=True)
strs.extend(nstrs)
return strs
elif (quote_char == '"' and
self.buf[i] == '\\' and i < (buflen-1)):
# check for special characters
special = None
if self.buf[i+1] == 'n':
special = '\n'
elif self.buf[i+1] == 't':
special = '\t'
elif self.buf[i+1] == '\"':
special = '\"'
elif self.buf[i+1] == '\\':
special = '\\'
elif self.strict_quoting and self.is_1_1:
error.err_add(self.errors, self.pos,
'ILLEGAL_ESCAPE', self.buf[i+1])
raise error.Abort
elif self.strict_quoting:
error.err_add(self.errors, self.pos,
'ILLEGAL_ESCAPE_WARN', self.buf[i+1])
if special != None:
res.append(self.buf[start:i])
res.append(special)
i = i + 1
start = i + 1
i = i + 1
# end-of-line
# first strip trailing whitespace in double quoted strings
# pre: self.buf[i-1] == '\n'
if i > 2 and self.buf[i-2] == '\r':
j = i - 3
else:
j = i - 2
k = j
while j >= 0 and self.buf[j].isspace():
j = j - 1
if j != k: # we found trailing whitespace
s = self.buf[start:j+1] + self.buf[k+1:i]
else:
s = self.buf[start:i]
res.append(s)
self.readline()
i = 0
if quote_char == '"':
# skip whitespace used for indentation
buflen = len(self.buf)
while (i < buflen and self.buf[i].isspace() and
i <= indentpos):
i = i + 1
if i == buflen:
# whitespace only on this line; keep it as is
i = 0
elif need_quote == True:
error.err_add(self.errors, self.pos, 'EXPECTED_QUOTED_STRING', ())
raise error.Abort
else:
# unquoted string
buflen = len(self.buf)
i = 0
while i < buflen:
if (self.buf[i].isspace() or self.buf[i] == ';' or
self.buf[i] == '{' or self.buf[i] == '}' or
self.buf[i:i+2] == '//' or self.buf[i:i+2] == '/*' or
self.buf[i:i+2] == '*/'):
res = self.buf[:i]
self.set_buf(i)
return [(res, '')]
i = i + 1
|
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/yang_parser.py#L151-L255
|
positions of substrings in string
|
python
|
def long_substr(data):
"""Return the longest common substring in a list of strings.
Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python
"""
substr = ''
if len(data) > 1 and len(data[0]) > 0:
for i in range(len(data[0])):
for j in range(len(data[0])-i+1):
if j > len(substr) and all(data[0][i:i+j] in x for x in data):
substr = data[0][i:i+j]
elif len(data) == 1:
substr = data[0]
return substr
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/text.py#L545-L558
|
positions of substrings in string
|
python
|
def _rsplit(expr, pat=None, n=-1):
"""
Split each string in the Series/Index by the given delimiter string,
starting at the end of the string and working to the front.
Equivalent to str.rsplit().
:param expr:
:param pat: Separator to split on. If None, splits on whitespace
:param n: None, 0 and -1 will be interpreted as return all splits
:return: sequence or scalar
"""
return _string_op(expr, RSplit, output_type=types.List(types.string),
_pat=pat, _n=n)
|
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/strings.py#L547-L560
|
positions of substrings in string
|
python
|
def str_ripper(self, text):
"""Got this code from here:
http://stackoverflow.com/questions/6116978/python-replace-multiple-strings
This method takes a set of strings, A, and removes all whole
elements of set A from string B.
Input: text string to strip based on instance attribute self.censor
Output: a stripped (censored) text string
"""
return self.pattern.sub(lambda m: self.rep[re.escape(m.group(0))], text)
|
https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/scripts/glotk-mer-reporter.py#L150-L160
|
positions of substrings in string
|
python
|
def parse_string_factory(
alg, sep, splitter, input_transform, component_transform, final_transform
):
"""
Create a function that will split and format a *str* into a tuple.
Parameters
----------
alg : ns enum
Indicate how to format and split the *str*.
sep : str
The string character to be inserted between adjacent numeric
objects in the returned tuple.
splitter : callable
A function the will accept a string and returns an iterable
of strings where the numbers are separated from the non-numbers.
input_transform : callable
A function to apply to the string input *before* applying
the *splitter* function. Must return a string.
component_transform : callable
A function that is operated elementwise on the output of
*splitter*. It must accept a single string and return either
a string or a number.
final_transform : callable
A function to operate on the return value as a whole. It
must accept a tuple and a string argument - the tuple
should be the result of applying the above functions, and the
string is the original input value. It must return a tuple.
Returns
-------
func : callable
A function that accepts string input and returns a tuple
containing the string split into numeric and non-numeric
components, where the numeric components are converted into
numeric objects. The first element is *always* a string,
and then alternates number then string. Intended to be
used as the *string_func* argument to *natsort_key*.
See Also
--------
natsort_key
input_string_transform_factory
string_component_transform_factory
final_data_transform_factory
"""
# Sometimes we store the "original" input before transformation,
# sometimes after.
orig_after_xfrm = not (alg & NS_DUMB and alg & ns.LOCALEALPHA)
original_func = input_transform if orig_after_xfrm else _no_op
normalize_input = _normalize_input_factory(alg)
def func(x):
# Apply string input transformation function and return to x.
# Original function is usually a no-op, but some algorithms require it
# to also be the transformation function.
x = normalize_input(x)
x, original = input_transform(x), original_func(x)
x = splitter(x) # Split string into components.
x = py23_filter(None, x) # Remove empty strings.
x = py23_map(component_transform, x) # Apply transform on components.
x = sep_inserter(x, sep) # Insert '' between numbers.
return final_transform(x, original) # Apply the final transform.
return func
|
https://github.com/SethMMorton/natsort/blob/ea0d37ef790b42c424a096e079edd9ea0d5717e3/natsort/utils.py#L333-L398
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.