Python string.join() Examples

The following are 30 code examples of string.join(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: pydoc.py    From meddle with MIT License 6 votes vote down vote up
def formattree(self, tree, modname, parent=None):
        """Produce HTML for a class tree as given by inspect.getclasstree()."""
        result = ''
        for entry in tree:
            if type(entry) is type(()):
                c, bases = entry
                result = result + '<dt><font face="helvetica, arial">'
                result = result + self.classlink(c, modname)
                if bases and bases != (parent,):
                    parents = []
                    for base in bases:
                        parents.append(self.classlink(base, modname))
                    result = result + '(' + join(parents, ', ') + ')'
                result = result + '\n</font></dt>'
            elif type(entry) is type([]):
                result = result + '<dd>\n%s</dd>\n' % self.formattree(
                    entry, modname, c)
        return '<dl>\n%s</dl>\n' % result 
Example #2
Source File: indic_normalize.py    From indic_nlp_library with MIT License 6 votes vote down vote up
def _init_to_anusvaara_relaxed(self):
        """
        `r1_nasal=re.compile(r'\\u0919\\u094D([\\u0915-\\u0918])')`
        """
            
        nasals_list=[0x19,0x1e,0x23,0x28,0x29,0x2e]    
        nasals_list_str=','.join([langinfo.offset_to_char(x,self.lang) for x in nasals_list])
        
        halant_offset=0x4d    
        anusvaara_offset=0x02    
        
        pat=re.compile(r'[{nasals_list_str}]{halant}'.format(
                nasals_list_str=nasals_list_str,
                halant=langinfo.offset_to_char(halant_offset,self.lang),
            ))
        
        repl_string='{anusvaara}'.format(anusvaara=langinfo.offset_to_char(anusvaara_offset,self.lang))

        self.pats_repls = (pat,repl_string) 
Example #3
Source File: ElementTree.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def _flush(self):
        if self._data:
            if self._last is not None:
                text = string.join(self._data, "")
                if self._tail:
                    assert self._last.tail is None, "internal error (tail)"
                    self._last.tail = text
                else:
                    assert self._last.text is None, "internal error (text)"
                    self._last.text = text
            self._data = []

    ##
    # Adds text to the current element.
    #
    # @param data A string.  This should be either an 8-bit string
    #    containing ASCII text, or a Unicode string. 
Example #4
Source File: kimmo.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def loadIntoWindow(self, filename, windowField):
        "Load rule/lexicon set from a text file directly into the window pane specified"
        # filename = args[0]
        # windowField = args[1]

        if filename:
	        filename = os.path.expanduser(filename)
	        f = read_kimmo_file(filename, self)
	        lines = f.readlines()
	        f.close()

	        text = []
	        for line in lines:
	            line = line.strip()
	            text.append(line)

	        # empty the window now that the file was valid
	        windowField.delete(1.0, Tkinter.END)
	
	        windowField.insert(1.0, '\n'.join(text))
	
	        return filename
        return ''	

    	# opens a load dialog for files of a specified type to be loaded into a specified window 
Example #5
Source File: ElementTree.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def _encode_entity(text, pattern=_escape):
    # map reserved and non-ascii characters to numerical entities
    def escape_entities(m, map=_escape_map):
        out = []
        append = out.append
        for char in m.group():
            text = map.get(char)
            if text is None:
                text = "&#%d;" % ord(char)
            append(text)
        return string.join(out, "")
    try:
        return _encode(pattern.sub(escape_entities, text), "ascii")
    except TypeError:
        _raise_serialization_error(text)

#
# the following functions assume an ascii-compatible encoding
# (or "utf-16") 
Example #6
Source File: msvccompiler.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def find_library_file (self, dirs, lib, debug=0):
        # Prefer a debugging library if found (and requested), but deal
        # with it if we don't have one.
        if debug:
            try_names = [lib + "_d", lib]
        else:
            try_names = [lib]
        for dir in dirs:
            for name in try_names:
                libfile = os.path.join(dir, self.library_filename (name))
                if os.path.exists(libfile):
                    return libfile
        else:
            # Oops, didn't find it in *any* of 'dirs'
            return None

    # find_library_file ()

    # Helper methods for using the MSVC registry settings 
Example #7
Source File: vssutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def VssLog(project, linePrefix = "", noLabels = 5, maxItems=150):
	lines = []
	num = 0
	labelNum = 0
	for i in project.GetVersions(constants.VSSFLAG_RECURSYES):
		num = num + 1
		if num > maxItems : break
		commentDesc = itemDesc = ""
		if i.Action[:5]=="Added":
			continue
		if len(i.Label):
			labelNum = labelNum + 1
			itemDesc = i.Action
		else:
			itemDesc = i.VSSItem.Name
			if str(itemDesc[-4:])==".dsp":
				continue
		if i.Comment:
			commentDesc ="\n%s\t%s" % (linePrefix, i.Comment)
		lines.append("%s%s\t%s%s" % (linePrefix, time.asctime(time.localtime(int(i.Date))), itemDesc, commentDesc))
		if labelNum > noLabels:
			break
	return string.join(lines,"\n") 
Example #8
Source File: vssutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def SubstituteInString(inString, evalEnv):
	substChar = "$"
	fields = string.split(inString, substChar)
	newFields = []
	for i in range(len(fields)):
		didSubst = 0
		strVal = fields[i]
		if i%2!=0:
			try:
				strVal = eval(strVal,evalEnv[0], evalEnv[1])
				newFields.append(strVal)
				didSubst = 1
			except:
				traceback.print_exc()
				print "Could not substitute", strVal
		if not didSubst:
			newFields.append(strVal)
	return string.join(map(str, newFields), "") 
Example #9
Source File: debugger.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args ):
    if module:
        keep = module.__name__
        keep = keep and (built_nodes.get(module) is None)
        if keep and hasattr(module, '__file__'):
            keep = string.lower(os.path.splitext(module.__file__)[1]) not in [".pyd", ".dll"]
#               keep = keep and module.__name__=='__main__'
    if module and keep:
#        print "keeping", module.__name__
        node = ModuleTreeNode(module)
        built_nodes[module] = node
        realNode = create_node_fn(*(node,)+create_node_args)
        node.realNode = realNode

        # Split into parent nodes.
        parts = string.split(module.__name__, '.')
        if parts[-1][:8]=='__init__': parts = parts[:-1]
        parent = string.join(parts[:-1], '.')
        parentNode = rootNode
        if parent:
            parentModule = sys.modules[parent]
            BuildModule(parentModule, built_nodes, rootNode, create_node_fn, create_node_args)
            if parentModule in built_nodes:
                parentNode = built_nodes[parentModule].realNode
        node.Attach(parentNode) 
Example #10
Source File: ImpactPacket.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def __str__(self):
        priorities = (
            'Best Effort',
            'Background',
            'Excellent Effort',
            'Critical Applications',
            'Video, < 100 ms latency and jitter',
            'Voice, < 10 ms latency and jitter',
            'Internetwork Control',
            'Network Control')

        pcp = self.get_pcp()
        return '\n'.join((
            '802.1Q header: 0x{0:08X}'.format(self.get_long(0)),
            'Priority Code Point: {0} ({1})'.format(pcp, priorities[pcp]),
            'Drop Eligible Indicator: {0}'.format(self.get_dei()),
            'VLAN Identifier: {0}'.format(self.get_vid()))) 
Example #11
Source File: make_meta1.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def make_invoke_method(self, nargs):
        params = ["PyString name"]
        args = ["name"]
        for i in range(nargs):
            params.append("PyObject arg%d" % i)
            args.append("arg%d" % i)
        ret = ["public override PyObject invoke(%s) {" % ", ".join(params)]
        ret.append("    if (name.interned) {")

        #TODO create switch clause when more than 3-8 matches
        for method in self.methods:
            if not method.is_invokable or len(method.param_list) != nargs:
                continue
            name = method.get_public_name()
            ret.append("        if (name == %s) return %s(%s);" %
                       (self.get_constant_string(name), name,
                        ", ".join(args[1:])))

        if len(ret) == 2: return []

        ret.append("    }")
        ret.append("    return base.invoke(%s);" % ", ".join(args))
        ret.append("}")
        return ret 
Example #12
Source File: ElementTree.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def tostring(element, encoding=None):
    class dummy:
        pass
    data = []
    file = dummy()
    file.write = data.append
    ElementTree(element).write(file, encoding)
    return string.join(data, "")

##
# Generic element structure builder.  This builder converts a sequence
# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
# #TreeBuilder.end} method calls to a well-formed element structure.
# <p>
# You can use this class to build an element structure using a custom XML
# parser, or a parser for some other XML-like format.
#
# @param element_factory Optional element factory.  This factory
#    is called to create new Element instances, as necessary. 
Example #13
Source File: pydoc.py    From meddle with MIT License 6 votes vote down vote up
def locate(path, forceload=0):
    """Locate an object by name or dotted path, importing as necessary."""
    parts = [part for part in split(path, '.') if part]
    module, n = None, 0
    while n < len(parts):
        nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
        if nextmodule: module, n = nextmodule, n + 1
        else: break
    if module:
        object = module
        for part in parts[n:]:
            try: object = getattr(object, part)
            except AttributeError: return None
        return object
    else:
        if hasattr(__builtin__, path):
            return getattr(__builtin__, path)

# --------------------------------------- interactive interpreter interface 
Example #14
Source File: sdist.py    From meddle with MIT License 6 votes vote down vote up
def prune_file_list(self):
        """Prune off branches that might slip into the file list as created
        by 'read_template()', but really don't belong there:
          * the build tree (typically "build")
          * the release tree itself (only an issue if we ran "sdist"
            previously with --keep-temp, or it aborted)
          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
        """
        build = self.get_finalized_command('build')
        base_dir = self.distribution.get_fullname()

        self.filelist.exclude_pattern(None, prefix=build.build_base)
        self.filelist.exclude_pattern(None, prefix=base_dir)

        # pruning out vcs directories
        # both separators are used under win32
        if sys.platform == 'win32':
            seps = r'/|\\'
        else:
            seps = '/'

        vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr',
                    '_darcs']
        vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps)
        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1) 
Example #15
Source File: platform.py    From meddle with MIT License 6 votes vote down vote up
def _norm_version(version, build=''):

    """ Normalize the version and build strings and return a single
        version string using the format major.minor.build (or patchlevel).
    """
    l = string.split(version,'.')
    if build:
        l.append(build)
    try:
        ints = map(int,l)
    except ValueError:
        strings = l
    else:
        strings = map(str,ints)
    version = string.join(strings[:3],'.')
    return version 
Example #16
Source File: inspect.py    From meddle with MIT License 6 votes vote down vote up
def formatargspec(args, varargs=None, varkw=None, defaults=None,
                  formatarg=str,
                  formatvarargs=lambda name: '*' + name,
                  formatvarkw=lambda name: '**' + name,
                  formatvalue=lambda value: '=' + repr(value),
                  join=joinseq):
    """Format an argument spec from the 4 values returned by getargspec.

    The first four arguments are (args, varargs, varkw, defaults).  The
    other four arguments are the corresponding optional formatting functions
    that are called to turn names and values into strings.  The ninth
    argument is an optional function to format the sequence of arguments."""
    specs = []
    if defaults:
        firstdefault = len(args) - len(defaults)
    for i, arg in enumerate(args):
        spec = strseq(arg, formatarg, join)
        if defaults and i >= firstdefault:
            spec = spec + formatvalue(defaults[i - firstdefault])
        specs.append(spec)
    if varargs is not None:
        specs.append(formatvarargs(varargs))
    if varkw is not None:
        specs.append(formatvarkw(varkw))
    return '(' + string.join(specs, ', ') + ')' 
Example #17
Source File: msvccompiler.py    From meddle with MIT License 6 votes vote down vote up
def find_exe(self, exe):
        """Return path to an MSVC executable program.

        Tries to find the program in several places: first, one of the
        MSVC program search paths from the registry; next, the directories
        in the PATH environment variable.  If any of those work, return an
        absolute path that is known to exist.  If none of them work, just
        return the original program name, 'exe'.
        """

        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        # didn't find it; try existing path
        for p in string.split(os.environ['Path'],';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe 
Example #18
Source File: msvccompiler.py    From meddle with MIT License 6 votes vote down vote up
def find_library_file (self, dirs, lib, debug=0):
        # Prefer a debugging library if found (and requested), but deal
        # with it if we don't have one.
        if debug:
            try_names = [lib + "_d", lib]
        else:
            try_names = [lib]
        for dir in dirs:
            for name in try_names:
                libfile = os.path.join(dir, self.library_filename (name))
                if os.path.exists(libfile):
                    return libfile
        else:
            # Oops, didn't find it in *any* of 'dirs'
            return None

    # find_library_file ()

    # Helper methods for using the MSVC registry settings 
Example #19
Source File: expressions.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def Start(self, callback):
        try:
            try:
                try:
                    self.result = eval(self.code, self.frame.f_globals, self.frame.f_locals)
                except SyntaxError:
                    exec self.code in self.frame.f_globals, self.frame.f_locals
                    self.result = ""
                self.hresult = 0
            except:
                l = traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1])
                # l is a list of strings with trailing "\n"
                self.result = string.join(map(lambda s:s[:-1], l), "\n")
                self.hresult = winerror.E_FAIL
        finally:
            self.isComplete = 1
            callback.onComplete() 
Example #20
Source File: platform.py    From meddle with MIT License 5 votes vote down vote up
def _abspath(path,

                 isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
                 normpath=os.path.normpath):

        if not isabs(path):
            path = join(getcwd(), path)
        return normpath(path) 
Example #21
Source File: platform.py    From meddle with MIT License 5 votes vote down vote up
def _platform(*args):

    """ Helper to format the platform string in a filename
        compatible format e.g. "system-version-machine".
    """
    # Format the platform string
    platform = string.join(
        map(string.strip,
            filter(len, args)),
        '-')

    # Cleanup some possible filename obstacles...
    replace = string.replace
    platform = replace(platform,' ','_')
    platform = replace(platform,'/','-')
    platform = replace(platform,'\\','-')
    platform = replace(platform,':','-')
    platform = replace(platform,';','-')
    platform = replace(platform,'"','-')
    platform = replace(platform,'(','-')
    platform = replace(platform,')','-')

    # No need to report 'unknown' information...
    platform = replace(platform,'unknown','')

    # Fold '--'s and remove trailing '-'
    while 1:
        cleaned = replace(platform,'--','-')
        if cleaned == platform:
            break
        platform = cleaned
    while platform[-1] == '-':
        platform = platform[:-1]

    return platform 
Example #22
Source File: platform.py    From meddle with MIT License 5 votes vote down vote up
def _follow_symlinks(filepath):

    """ In case filepath is a symlink, follow it until a
        real file is reached.
    """
    filepath = _abspath(filepath)
    while os.path.islink(filepath):
        filepath = os.path.normpath(
            os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
    return filepath 
Example #23
Source File: pydoc.py    From meddle with MIT License 5 votes vote down vote up
def ttypager(text):
    """Page through text on a text terminal."""
    lines = split(plain(text), '\n')
    try:
        import tty
        fd = sys.stdin.fileno()
        old = tty.tcgetattr(fd)
        tty.setcbreak(fd)
        getchar = lambda: sys.stdin.read(1)
    except (ImportError, AttributeError):
        tty = None
        getchar = lambda: sys.stdin.readline()[:-1][:1]

    try:
        r = inc = os.environ.get('LINES', 25) - 1
        sys.stdout.write(join(lines[:inc], '\n') + '\n')
        while lines[r:]:
            sys.stdout.write('-- more --')
            sys.stdout.flush()
            c = getchar()

            if c in ('q', 'Q'):
                sys.stdout.write('\r          \r')
                break
            elif c in ('\r', '\n'):
                sys.stdout.write('\r          \r' + lines[r] + '\n')
                r = r + 1
                continue
            if c in ('b', 'B', '\x1b'):
                r = r - inc - inc
                if r < 0: r = 0
            sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
            r = r + inc

    finally:
        if tty:
            tty.tcsetattr(fd, tty.TCSAFLUSH, old) 
Example #24
Source File: pydoc.py    From meddle with MIT License 5 votes vote down vote up
def indent(self, text, prefix='    '):
        """Indent text by prepending a given prefix to each line."""
        if not text: return ''
        lines = split(text, '\n')
        lines = map(lambda line, prefix=prefix: prefix + line, lines)
        if lines: lines[-1] = rstrip(lines[-1])
        return join(lines, '\n') 
Example #25
Source File: fancy_getopt.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def getopt (self, args=None, object=None):
        """Parse command-line options in args. Store as attributes on object.

        If 'args' is None or not supplied, uses 'sys.argv[1:]'.  If
        'object' is None or not supplied, creates a new OptionDummy
        object, stores option values there, and returns a tuple (args,
        object).  If 'object' is supplied, it is modified in place and
        'getopt()' just returns 'args'; in both cases, the returned
        'args' is a modified copy of the passed-in 'args' list, which
        is left untouched.
        """
        if args is None:
            args = sys.argv[1:]
        if object is None:
            object = OptionDummy()
            created_object = 1
        else:
            created_object = 0

        self._grok_option_table()

        short_opts = string.join(self.short_opts)
        try:
            opts, args = getopt.getopt(args, short_opts, self.long_opts)
        except getopt.error, msg:
            raise DistutilsArgError, msg 
Example #26
Source File: pydoc.py    From meddle with MIT License 5 votes vote down vote up
def _docdescriptor(self, name, value, mod):
        results = []
        push = results.append

        if name:
            push('<dl><dt><strong>%s</strong></dt>\n' % name)
        if value.__doc__ is not None:
            doc = self.markup(getdoc(value), self.preformat)
            push('<dd><tt>%s</tt></dd>\n' % doc)
        push('</dl>\n')

        return ''.join(results) 
Example #27
Source File: pydoc.py    From meddle with MIT License 5 votes vote down vote up
def repr1(self, x, level):
        if hasattr(type(x), '__name__'):
            methodname = 'repr_' + join(split(type(x).__name__), '_')
            if hasattr(self, methodname):
                return getattr(self, methodname)(x, level)
        return cram(stripid(repr(x)), self.maxother) 
Example #28
Source File: inspect.py    From meddle with MIT License 5 votes vote down vote up
def joinseq(seq):
    if len(seq) == 1:
        return '(' + seq[0] + ',)'
    else:
        return '(' + string.join(seq, ', ') + ')' 
Example #29
Source File: pydoc.py    From meddle with MIT License 5 votes vote down vote up
def formattree(self, tree, modname, parent=None, prefix=''):
        """Render in text a class tree as returned by inspect.getclasstree()."""
        result = ''
        for entry in tree:
            if type(entry) is type(()):
                c, bases = entry
                result = result + prefix + classname(c, modname)
                if bases and bases != (parent,):
                    parents = map(lambda c, m=modname: classname(c, m), bases)
                    result = result + '(%s)' % join(parents, ', ')
                result = result + '\n'
            elif type(entry) is type([]):
                result = result + self.formattree(
                    entry, modname, c, prefix + '    ')
        return result 
Example #30
Source File: pydoc.py    From meddle with MIT License 5 votes vote down vote up
def _docdescriptor(self, name, value, mod):
        results = []
        push = results.append

        if name:
            push(self.bold(name))
            push('\n')
        doc = getdoc(value) or ''
        if doc:
            push(self.indent(doc))
            push('\n')
        return ''.join(results)