def color(string, color=None): """ Change text color for the Linux terminal. """ attr = [] # bold attr.append('1') if color: if color.lower() == "red": attr.append('31') elif color.lower() == "yellow": attr.append('33') elif color.lower() == "green": attr.append('32') elif color.lower() == "blue": attr.append('34') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) else: if string.startswith("[!]"): attr.append('31') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) elif string.startswith("[+]"): attr.append('32') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) elif string.startswith("[*]"): attr.append('34') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) else: return string
def color(string, color='', graphic=''): """ Change text color for the Linux terminal. Args: string (str): String to colorify color (str): Color to colorify the string in the following list: black, red, green, yellow, blue, purple, cyan, gr[ae]y graphic (str): Graphic to append to the beginning of the line """ if not color: if string.startswith("[!] "): color = 'red' elif string.startswith("[+] "): color = 'green' elif string.startswith("[*] "): color = 'blue' else: color = 'normal' if color not in colors: print(colors['red'] + 'Color not found: {}'.format(color) + colors['normal']) return if color: return colors[color] + graphic + string + colors['normal'] else: return string + colors['normal']
def color(string, color=None): """ Change text color for the Linux terminal. """ attr = [] # bold attr.append("1") if color: if color.lower() == "red": attr.append("31") elif color.lower() == "green": attr.append("32") elif color.lower() == "blue": attr.append("34") return "\x1b[%sm%s\x1b[0m" % (";".join(attr), string) else: if string.startswith("[!]"): attr.append("31") return "\x1b[%sm%s\x1b[0m" % (";".join(attr), string) elif string.startswith("[+]"): attr.append("32") return "\x1b[%sm%s\x1b[0m" % (";".join(attr), string) elif string.startswith("[*]"): attr.append("34") return "\x1b[%sm%s\x1b[0m" % (";".join(attr), string) else: return string
def expand_tilde(string): """ Return an expanded version of the string by replacing a leading tilde with %HOME% (if defined) or %USERPROFILE%. """ if 'HOME' in os.environ.keys(): home_var = 'HOME' else: home_var = 'USERPROFILE' if string.startswith('~') or string.startswith('"~'): string = string.replace('~', '%' + home_var + '%', 1) return string
def cleanExtension(string): """ @param string: The extension to clean @type string: str @return: The cleaned extension in <i>.ext</i> format. @rtype: str """ if string.startswith('*'): string = string[1:] if not string.startswith('.'): string = '.' + string return string
def is_multiline_start(self, string): start_quote = False end_quote = False if string.startswith('"') and not string.startswith('"""'): start_quote = True if string.endswith('"') and not string.endswith('"""'): end_quote = True # line that only contains a quote if len(string.strip()) == 1 and (start_quote or end_quote): return True return start_quote and (start_quote and not end_quote)
def is_multiline_end(self, string): start_quote = False end_quote = False if string.startswith("\"") and not string.startswith("\"\"\""): start_quote = True if string.endswith("\"") and not string.endswith("\"\"\""): end_quote = True # line that only contains a quote if len(string) == 1 and (start_quote or end_quote): return True return end_quote and (end_quote and not start_quote)
def unQuote(string): """ @param string: @type string: @return: The stripped string. @rtype: string """ if string.startswith('"') and string.endswith('"'): string = string[1:-1] elif string.startswith("'") and string.endswith("'"): string = string[1:-1] return string
def decode(cls, string, base): """ Decode a Base X encoded string into a decimal number @param string: The encoded number, in str format @param base: The base from which to convert the number @return : Number in decimal encoding @rvalue : int """ if base < 2 or base > 62: raise ValueError('Illegal base') num = 0 # If ``string`` is padded with zeros, remove them while 1: if string != '0' and string.startswith('0'): string = string[1:] else: break for power, char in enumerate(string[::-1]): try: index = cls.ALPHABET.index(char) except ValueError: # ``char`` is not contained in the alphabet raise ValueError('Number contains illegal digits') if index >= base: raise ValueError('Number contains illegal digits') num += index * (base ** power) return num
def string_remove_quotes(string): if type(string) not in (str, unicode): return string for char in ('"', "'"): if string.startswith(char) and string.endswith(char): return string[1:-1]
def _check_conflict(self, option): conflict_opts = [] for opt in option._short_opts: if self._short_opt.has_key(opt): conflict_opts.append((opt, self._short_opt[opt])) for opt in option._long_opts: if self._long_opt.has_key(opt): conflict_opts.append((opt, self._long_opt[opt])) if conflict_opts: handler = self.conflict_handler if handler == "error": opts = [] for co in conflict_opts: opts.append(co[0]) raise errors.OptionConflictError( "conflicting option string(s): %s" % string.join(opts, ", "), option) elif handler == "resolve": for (opt, c_option) in conflict_opts: if string.startswith(opt, "--"): c_option._long_opts.remove(opt) del self._long_opt[opt] else: c_option._short_opts.remove(opt) del self._short_opt[opt] if not (c_option._short_opts or c_option._long_opts): c_option.container.option_list.remove(c_option)
def ltrim(string, prefix): ''' Trim all prefixes from string. ''' length = len(prefix) while string.startswith(prefix): string = string[length:] return string
def fromPDBrecord(cls,string): if string.startswith('ATOM'): name = string[12:16].strip() x = float(string[30:38].strip()) y = float(string[38:46].strip()) z = float(string[46:54].strip()) return cls(name,[x,y,z]) else: sys.exit(1)
def lchop(string, prefix): """Removes a prefix from string :param string: String, possibly prefixed with prefix :param prefix: Prefix to remove from string :returns: string without the prefix """ if string.startswith(prefix): return string[len(prefix):] return string
def color(string, color='', graphic=''): """ Change text color for the Linux terminal. Args: string (str): String to colorify color (str): Color to colorify the string in the following list: black, red, green, yellow, blue, purple, cyan, gr[ae]y graphic (str): Graphic to append to the beginning of the line """ colors = { 'normal' : "\x1b[0m", 'black' : "\x1b[30m", 'red' : "\x1b[31m", 'green' : "\x1b[32m", 'yellow' : "\x1b[33m", 'blue' : "\x1b[34m", 'purple' : "\x1b[35m", 'cyan' : "\x1b[36m", 'grey' : "\x1b[90m", 'gray' : "\x1b[90m", 'bold' : "\x1b[1m" } if not color: if string.startswith("[!] "): color = 'red' elif string.startswith("[+] "): color = 'green' elif string.startswith("[*] "): color = 'blue' else: color = 'normal' if color not in colors: print colors['red'] + 'Color not found: {}'.format(color) + colors['normal'] return if color: return colors[color] + graphic + string + colors['normal'] else: return string + colors['normal']
def remove_prefix(string, prefix): """ This funtion removes the given prefix from a string, if the string does indeed begin with the prefix; otherwise, it returns the string unmodified. """ if string.startswith(prefix): return string[len(prefix):] else: return string
def set_usage(self, usage): if usage is None: self.usage = _("%prog [options]") elif usage is SUPPRESS_USAGE: self.usage = None # For backwards compatibility with Optik 1.3 and earlier. elif string.startswith(usage, "usage:" + " "): self.usage = usage[7:] else: self.usage = usage
def dequote(string): """Takes string which may or may not be quoted and unquotes it. It only considers double quotes. This function does NOT consider parenthised lists to be quoted. """ if string and string.startswith('"') and string.endswith('"'): string = string[1:-1] # Strip off the surrounding quotes. string = string.replace('\\"', '"') string = string.replace('\\\\', '\\') return string
def find_in_bor(root, string): #print string if string == 'le': for i in range(len(root.arr)): print root.arr[i].string for i in range(len(root.arr)): if root.arr[i].string == string: return True if root.arr[i].is_leaf else False; elif string.startswith(root.arr[i].string): return find_in_bor(root.arr[i], string[len(root.arr[i].string):]) return False
def string_safe_shell(string): if string.startswith("'") and string.endswith("'"): return string else: return string_escape_char( string, str( '&();|\n'+ # Control operators '<>'+ # Redirection operators '!*?[]'+ # Shell patterns '$' # Variables ) )
def trim(string, xfix): ''' Trim all prefixes or suffixes of xfix from string. ''' if is_string(string): string = string.encode() if is_string(xfix): xfix = xfix.encode() length = len(xfix) while string.startswith(xfix): string = string[length:] while string.endswith(xfix): string = string[:-length] return string
def safe_prepend(prepend_string, string): """Prepend to string non-destructively Ex: safe_prepend('EUCTR', 'EUCTR12345678') => 'EUCTR12345678' Args: prepend_string: string to prepend string: string to prepend to """ if string is None: return None if not string.startswith(prepend_string): string = '%s%s' % (prepend_string, string) return string
def common_prefix(strings): """ Given a list of strings, return the common prefix between all these strings. """ ref = strings[0] prefix = '' for size in range(len(ref)): test_prefix = ref[:size+1] for string in strings[1:]: if not string.startswith(test_prefix): return prefix prefix = test_prefix return prefix
def _close_fstring_if_necessary(fstring_stack, string, start_pos, additional_prefix): for fstring_stack_index, node in enumerate(fstring_stack): if string.startswith(node.quote): token = PythonToken( FSTRING_END, node.quote, start_pos, prefix=additional_prefix, ) additional_prefix = '' assert not node.previous_lines del fstring_stack[fstring_stack_index:] return token, '', len(node.quote) return None, additional_prefix, 0
def parse(cls, string, default_scheme='http', encoding='utf8'): '''Parse and return a new info from the given URL. Returns: :class:`URLInfo` Raises: :class:`ValueError` if the URL is seriously malformed ''' if not string: raise ValueError('Empty URL') assert isinstance(string, str) url_split_result = urllib.parse.urlsplit(string) if not url_split_result.scheme: url_split_result = urllib.parse.urlsplit( '{0}://{1}'.format(default_scheme, string) ) if url_split_result.scheme in ('http', 'https'): if string.startswith('//'): url_split_result = urllib.parse.urlsplit( '{0}:{1}'.format(url_split_result.scheme, string) ) elif not url_split_result.hostname: raise ValueError('Missing hostname for HTTP protocol.') port = url_split_result.port if not port: port = 80 if url_split_result.scheme == 'http' else 443 return URLInfo( url_split_result.scheme, url_split_result.netloc, cls.normalize_path(url_split_result.path, encoding=encoding), cls.normalize_query(url_split_result.query, encoding=encoding), url_split_result.fragment, url_split_result.username, url_split_result.password, cls.normalize_hostname(url_split_result.hostname), port, string, cls.normalize(url_split_result, encoding=encoding), wpull.util.normalize_codec_name(encoding), )
def i18nize(self, action): # Takes the current string, generates a i18n key. # Replaces the selection with the t('<<key>>'), # Adds the locale.yml string to clipboard (key: Original String) doc = self._window.get_active_document() if not doc: return selection = doc.get_selection_bounds() current_pos_mark = doc.get_insert() if not len(selection): return start, end = selection string = start.get_slice(end) i18n_key = re.sub(r'[\W]+', '', string.lower().strip().replace(' ', '_')) i18n_string = re.sub(r'[\'"]+', '', string.strip()) locale_config = '{0}: {1}'.format(i18n_key, i18n_string) # If string is quoted, string is already being evaluated. # If not quoted, string needs the '=' evaluation added. if string.startswith("'") or string.startswith('"'): view_string = 't(".{0}")'.format(i18n_key) else: view_string = '= t(".{0}")'.format(i18n_key) doc.delete(start, end) doc.insert(start, view_string) cb = gtk.Clipboard() cb.set_text(locale_config) cb.store()
def isvalid(string): # checks title start with wrong words for s in exe_start: if string.startswith(s): return False # checks title start with lower-case character if string[0:1].islower(): return False # checks title end with wrong words for s in exe_ending: if string.endswith(s): return False # check title of wrong words for s in exe_title: if s == string: return False return True
def add_info(string, reg): """ This function ... :param string: :param reg: :return: """ start_chars = " #" if not string.startswith("#") else " " if reg.has_info: string += start_chars if reg.has_label: string += " text={" + reg.label + "}" if reg.has_meta: if "text" in reg.meta: string += " text={" + reg.meta["text"] + "}" string += " " + " ".join(key + "=" + value for key, value in reg.meta.items() if types.is_string_type(value) and key != "text") if reg.has_appearance: string += " " + " ".join(key + "=" + value for key, value in reg.appearance.items()) return string
def get_translation_dicts(self): """ Returns dictionaries for the translation of keysyms to strings and from strings to keysyms. """ keysym_to_string_dict = {} string_to_keysym_dict = {} #XK loads latin1 and miscellany on its own; load latin2-4 and greek Xlib.XK.load_keysym_group('latin2') Xlib.XK.load_keysym_group('latin3') Xlib.XK.load_keysym_group('latin4') Xlib.XK.load_keysym_group('greek') #Make a standard dict and the inverted dict for string, keysym in Xlib.XK.__dict__.items(): if string.startswith('XK_'): string_to_keysym_dict[string[3:]] = keysym keysym_to_string_dict[keysym] = string[3:] return keysym_to_string_dict, string_to_keysym_dict
def extractSummary2(soup): summaries_dict = {} # find summary for the older files #summary = soup.find(name='div', class_='summary') summary = soup.find(class_='profile-section', id='summary') if summary: temp_summ = [] summary_text = '' for string in summary.stripped_strings: temp_summ.append(string) for string in temp_summ: string = string.lower() if not string.startswith('summary'): summary_text += ' ' + string summaries_dict["summary"] = summary_text else: summaries_dict["summary"] = "Missing" summaries_dict["summary"] = cleanSummaries(summaries_dict["summary"]) return summaries_dict
def title_case(string): """Convert to title case (like BibTeX's built-in "change.case$"). Raises InputError if the title string contains syntax errors. """ # See "@<Perform the case conversion@>" out = [] level, prev_colon, pos = 0, False, 0 while pos < len(string): keep = (pos == 0 or (prev_colon and string[pos - 1] in ' \t\n')) if level == 0 and string.startswith('{\\', pos) and not keep: # Special character out.append(string[pos]) pos += 1 level += 1 while level and pos < len(string): if string[pos] == '\\': m = CS_RE.match(string, pos) if m: if m.group() in _CONTROL_SEQS: # Lower case control sequence out.append(m.group().lower()) else: # Unknown control sequence, keep case out.append(m.group()) pos = m.end() continue elif string[pos] == '{': level += 1 elif string[pos] == '}': level -= 1 # Lower-case non-control sequence out.append(string[pos].lower()) pos += 1 prev_colon = False continue # Handle braces char = string[pos] if char == '{': level += 1 elif char == '}': if level == 0: raise ValueError('unexpected }') level -= 1 # Handle colon state if char == ':': prev_colon = True elif char not in ' \t\n': prev_colon = False # Change case of a regular character if level > 0 or keep: out.append(string[pos]) else: out.append(string[pos].lower()) pos += 1 return ''.join(out)
def is_var(string): return string.startswith('$')
def tab(string): if string.startswith("\t"): return True return False
def _removeprefix(string: str, prefix: str) -> str: if prefix and string.startswith(prefix): return string[len(prefix):] return string
def ParseValue(string): string = string.strip() if string.startswith('[') and string.endswith(']'): return string.lstrip('[').rstrip(']').split() else: return string
def Remove_Formatting(string, color=True, bold=True, italic=True, spaces=True, dots=True, dashes=True): """ This will cleanup a Kodi string, it can remove color, bold and italic tags as well as preceding spaces, dots and dashes. Particularly useful if you want to show the names of add-ons in alphabetical order where add-on names have deliberately had certain formatting added to them to get them to always show at the top of lists. CODE: Remove_Formatting(string, [color, bold, italic, spaces, dots, dashes]) AVAILABLE PARAMS: (*) string - This is string you want to remove formatting from. color - By default this is set to true and all references to the color tag will be removed, set this to false if you don't want color formatting removed. bold - By default this is set to true and all references to the bold tag will be removed, set this to false if you don't want bold formatting removed. italic - By default this is set to true and all references to the italic tag will be removed, set this to false if you don't want italic formatting removed. spaces - By default this is set to true and any spaces at the start of the text will be removed, set this to false if you don't want the spaces removed. dots - By default this is set to true and any dots (.) at the start of the text will be removed, set this to false if you don't want the dots removed. dashes - By default this is set to true and any dashes (-) at the start of the text will be removed, set this to false if you don't want the dashes removed. EXAMPLE CODE: mystring = '...-- [I]This[/I] is the [COLOR dodgerblue]ORIGINAL[/COLOR] [B][COLOR cyan]TEXT[/COLOR][/B]' dialog.ok('ORIGINAL TEXT','Below is the original text we\'re going to try and clean up:[CR]%s'%mystring) dialog.ok('DOTS REMOVED','[COLOR gold]Original:[/COLOR][CR]%s[CR][COLOR gold]This is with only dots set to True:[/COLOR][CR]%s'%(mystring,koding.Remove_Formatting(mystring, color=False, bold=False, italic=False, spaces=False, dots=True, dashes=False))) dialog.ok('DOTS & DASHES REMOVED','[COLOR gold]Original:[/COLOR][CR]%s[CR][COLOR gold]This is with dots & dashes set to True:[/COLOR][CR]%s'%(mystring,koding.Remove_Formatting(mystring, color=False, bold=False, italic=False, spaces=False, dots=True, dashes=True))) dialog.ok('DOTS, DASHES & SPACES REMOVED','[COLOR gold]Original:[/COLOR][CR]%s[CR][COLOR gold]This is with dots, dashes & spaces set to True:[/COLOR][CR]%s'%(mystring,koding.Remove_Formatting(mystring, color=False, bold=False, italic=False, spaces=True, dots=True, dashes=True))) dialog.ok('ALL FORMATTING REMOVED','[COLOR gold]Original:[/COLOR][CR]%s[CR][COLOR gold]This is with all options set to True:[/COLOR][CR]%s'%(mystring,koding.Remove_Formatting(mystring))) ~""" import re if color: if '[COLOR' in string: string = string.replace('[/COLOR]', '') colorlist = re.compile(r'\[COLOR(.+?)\]').findall(string) for colors in colorlist: string = string.replace('[COLOR%s]' % colors, '') if spaces: string = string.strip() if bold: string = string.replace('[B]', '').replace('[/B]', '') if spaces: string = string.strip() if italic: string = string.replace('[I]', '').replace('[/I]', '') if spaces: string = string.strip() if dots: while string.startswith('.'): string = string[1:] if spaces: string = string.strip() if dashes: while string.startswith('-'): string = string[1:] if spaces: string = string.strip() if spaces: string = string.strip() return string
def from_string(cls, string: str): """Parse an answer string.""" correct = string.startswith('*') answer = string[1:] if correct else string return cls(answer, correct)
def prefix_string(self, string): prefix = self.get_prefix() if string.startswith(prefix): return string return "{}_{}".format(prefix, string)
def parse(cls, string, default_scheme='http', encoding='utf8', normalization_params=None, use_cache=True): '''Parse and return a new info from the given URL. Args: string (str): The URL. default_scheme (str): The default scheme if not specified. encoding (str): The name of the encoding to be used for IRI support. normalization_params: Instance of :class:`NormalizationParams` describing further normalization settings. Returns: :class:`URLInfo` Raises: `ValueError`: The URL is seriously malformed. ''' if not string: raise ValueError('Empty URL') assert isinstance(string, str) cache_key = (string, default_scheme, encoding, normalization_params) if use_cache: try: return cls.cache[cache_key] except KeyError: pass if normalization_params is None: normalization_params = NormalizationParams() url_split_result = urllib.parse.urlsplit(string) if not url_split_result.scheme: url_split_result = urllib.parse.urlsplit( '{0}://{1}'.format(default_scheme, string) ) if url_split_result.scheme in ('http', 'https'): if string.startswith('//'): url_split_result = urllib.parse.urlsplit( '{0}:{1}'.format(url_split_result.scheme, string) ) elif not url_split_result.hostname: raise ValueError('Missing hostname for HTTP protocol.') port = url_split_result.port if not port: port = 80 if url_split_result.scheme == 'http' else 443 url_info = URLInfo( url_split_result.scheme, url_split_result.netloc, cls.normalize_path(url_split_result.path, encoding=encoding), cls.normalize_query( url_split_result.query, encoding=encoding, sort=normalization_params.sort_query, always_delim=normalization_params.always_delim_query, ), url_split_result.fragment, url_split_result.username, url_split_result.password, cls.normalize_hostname(url_split_result.hostname), port, string, wpull.string.normalize_codec_name(encoding), ) if use_cache: cls.cache[cache_key] = url_info return url_info
def parse_string_header(string: str) -> str: """For use when parsing nested data from tabular data formats, such as spreadsheets""" if string.startswith("{"): return ".".join(re.findall(r'(\w+)\b', string, re.DOTALL)) else: return string
def startat(self, string, starting): if string.startswith(starting): return len(starting) return 0