Python string.join() Examples

The following are 30 code examples for showing how to use string.join(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: razzy-spinner   Author: rafasashi   File: ElementTree.py    License: 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 2
Project: razzy-spinner   Author: rafasashi   File: ElementTree.py    License: 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 3
Project: razzy-spinner   Author: rafasashi   File: ElementTree.py    License: 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
Project: razzy-spinner   Author: rafasashi   File: kimmo.py    License: 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
Project: indic_nlp_library   Author: anoopkunchukuttan   File: indic_normalize.py    License: 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 6
Project: CVE-2017-7494   Author: joxeankoret   File: ImpactPacket.py    License: 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 7
Project: meddle   Author: glmcdona   File: msvccompiler.py    License: 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 8
Project: meddle   Author: glmcdona   File: msvccompiler.py    License: 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 9
Project: meddle   Author: glmcdona   File: sdist.py    License: 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 10
Project: meddle   Author: glmcdona   File: pydoc.py    License: 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 11
Project: meddle   Author: glmcdona   File: pydoc.py    License: 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 12
Project: meddle   Author: glmcdona   File: platform.py    License: 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 13
Project: meddle   Author: glmcdona   File: inspect.py    License: 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 14
Project: ironpython2   Author: IronLanguages   File: make_meta1.py    License: 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 15
Project: ironpython2   Author: IronLanguages   File: expressions.py    License: 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 16
Project: ironpython2   Author: IronLanguages   File: debugger.py    License: 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 17
Project: ironpython2   Author: IronLanguages   File: vssutil.py    License: 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 18
Project: ironpython2   Author: IronLanguages   File: vssutil.py    License: 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 19
Project: ironpython2   Author: IronLanguages   File: msvccompiler.py    License: 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 20
Project: razzy-spinner   Author: rafasashi   File: kimmo.py    License: GNU General Public License v3.0 5 votes vote down vote up
def read_kimmo_file(filename, gui=None):
    path = os.path.expanduser(filename)
    try:
        f = open(path, 'r')
    except IOError, e:
        path = os.path.join(get_basedir(), "kimmo", filename)
        try:
            f = open(path, 'r')
        except IOError, e:
            if gui:
                gui.guiError(str(e))
            else:
                print str(e)
            print "FAILURE"
            return "" 
Example 21
Project: indic_nlp_library   Author: anoopkunchukuttan   File: indic_normalize.py    License: MIT License 5 votes vote down vote up
def _normalize_vowel_ending(self,text):
        return ' '.join([ self.fn_vowel_ending(w) for w in text.split(' ') ]) 
Example 22
Project: bayeslite   Author: probcomp   File: Transitions.py    License: Apache License 2.0 5 votes vote down vote up
def __str__(self):
    map_strs = []
    map = self.map
    n = len(map)
    i = 0
    while i < n:
      code = map[i]
      if code == -maxint:
        code_str = "-inf"
      elif code == maxint:
        code_str = "inf"
      else:
        code_str = str(code)
      map_strs.append(code_str)
      i = i + 1
      if i < n:
        map_strs.append(state_set_str(map[i]))
      i = i + 1
    special_strs = {}
    for event, set in self.special.items():
      special_strs[event] = state_set_str(set)
    return "[%s]+%s" % (
      string.join(map_strs, ","), 
      special_strs
    )
  
  # --------------------- Debugging methods ----------------------- 
Example 23
Project: bayeslite   Author: probcomp   File: Transitions.py    License: Apache License 2.0 5 votes vote down vote up
def state_set_str(set):
  state_list = set.keys()
  str_list = []
  for state in state_list:
    str_list.append("S%d" % state.number)
  return "[%s]" % string.join(str_list, ",") 
Example 24
Project: bayeslite   Author: probcomp   File: Machines.py    License: Apache License 2.0 5 votes vote down vote up
def ranges_to_string(self, range_list):
    return string.join(map(self.range_to_string, range_list), ",") 
Example 25
Project: bayeslite   Author: probcomp   File: Regexps.py    License: Apache License 2.0 5 votes vote down vote up
def calc_str(self):
		return "Seq(%s)" % string.join(map(str, self.re_list), ",") 
Example 26
Project: bayeslite   Author: probcomp   File: Regexps.py    License: Apache License 2.0 5 votes vote down vote up
def calc_str(self):
		return "Alt(%s)" % string.join(map(str, self.re_list), ",") 
Example 27
Project: CVE-2017-7494   Author: joxeankoret   File: ImpactPacket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list_as_hex(self, aList):
        if len(aList):
            ltmp = []
            line = []
            count = 0
            for byte in aList:
                if not (count % 2):
                    if (count % 16):
                        ltmp.append(' ')
                    else:
                        ltmp.append(' '*4)
                        ltmp.append(string.join(line, ''))
                        ltmp.append('\n')
                        line = []
                if chr(byte) in Header.packet_printable:
                    line.append(chr(byte))
                else:
                    line.append('.')
                ltmp.append('%.2x' % byte)
                count += 1
            if (count%16):
                left = 16 - (count%16)
                ltmp.append(' ' * (4+(left / 2) + (left*2)))
                ltmp.append(string.join(line, ''))
                ltmp.append('\n')
            return ltmp
        else:
            return [] 
Example 28
Project: CVE-2017-7494   Author: joxeankoret   File: ImpactPacket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __str__(self):
        ltmp = self.list_as_hex(self.get_bytes().tolist())

        if self.child():
            ltmp.append(['\n', str(self.child())])

        if len(ltmp)>0:
            return string.join(ltmp, '')
        else:
            return '' 
Example 29
Project: CVE-2017-7494   Author: joxeankoret   File: ImpactPacket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __str__(self):
        ss = []
        alen = self.get_addr_len()
        addr = hexlify(self.get_addr()[0:alen])
        ss.append("Linux SLL: addr=%s type=`%s'" % (addr, self.get_type_desc()))
        if self.child():
            ss.append(str(self.child()))

        return '\n'.join(ss) 
Example 30
Project: django-angularjs-blog   Author: bluedazzle   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create_random_str(count=4):
    if count > 62:
        return 'too long str'
    return string.join(random.sample('ZYXWVUTSRQPONMLKJIHGFEDCBA1234567890zyxwvutsrqponmlkjihgfedcba', count)).replace(" ", "")