Python string.strip() Examples

The following are 30 code examples for showing how to use string.strip(). 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: cf-mendix-buildpack   Author: mendix   File: munin.py    License: Apache License 2.0 6 votes vote down vote up
def print_requests_config(name, stats):
    print("multigraph mxruntime_requests_%s" % name)
    print("graph_args --base 1000 -l 0")
    print("graph_vlabel Requests per second")
    print("graph_title %s - MxRuntime Requests" % name)
    print("graph_category Mendix")
    print(
        "graph_info This graph shows the amount of requests this MxRuntime handles"
    )
    for sub in stats["requests"].keys():
        substrip = "_" + string.strip(sub, "/").replace("-", "_")
        if sub != "":
            subname = sub
        else:
            subname = "/"
        print("%s.label %s" % (substrip, subname))
        print("%s.draw LINE1" % substrip)
        print(
            "%s.info amount of requests this MxRuntime handles on %s"
            % (substrip, subname)
        )
        print("%s.type DERIVE" % substrip)
        print("%s.min 0" % substrip)
    print("") 
Example 2
Project: meddle   Author: glmcdona   File: bdist_rpm.py    License: MIT License 6 votes vote down vote up
def _format_changelog(self, changelog):
        """Format the changelog correctly and convert it to a list of strings
        """
        if not changelog:
            return changelog
        new_changelog = []
        for line in string.split(string.strip(changelog), '\n'):
            line = string.strip(line)
            if line[0] == '*':
                new_changelog.extend(['', line])
            elif line[0] == '-':
                new_changelog.append(line)
            else:
                new_changelog.append('  ' + line)

        # strip trailing newline inserted by first changelog entry
        if not new_changelog[0]:
            del new_changelog[0]

        return new_changelog

    # _format_changelog()

# class bdist_rpm 
Example 3
Project: meddle   Author: glmcdona   File: pydoc.py    License: MIT License 6 votes vote down vote up
def source_synopsis(file):
    line = file.readline()
    while line[:1] == '#' or not strip(line):
        line = file.readline()
        if not line: break
    line = strip(line)
    if line[:4] == 'r"""': line = line[1:]
    if line[:3] == '"""':
        line = line[3:]
        if line[-1:] == '\\': line = line[:-1]
        while not strip(line):
            line = file.readline()
            if not line: break
        result = strip(split(line, '"""')[0])
    else: result = None
    return result 
Example 4
Project: meddle   Author: glmcdona   File: platform.py    License: MIT License 6 votes vote down vote up
def _syscmd_uname(option,default=''):

    """ Interface to the system's uname command.
    """
    if sys.platform in ('dos','win32','win16','os2'):
        # XXX Others too ?
        return default
    try:
        f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
    except (AttributeError,os.error):
        return default
    output = string.strip(f.read())
    rc = f.close()
    if not output or rc:
        return default
    else:
        return output 
Example 5
Project: ironpython2   Author: IronLanguages   File: bdist_rpm.py    License: Apache License 2.0 6 votes vote down vote up
def _format_changelog(self, changelog):
        """Format the changelog correctly and convert it to a list of strings
        """
        if not changelog:
            return changelog
        new_changelog = []
        for line in string.split(string.strip(changelog), '\n'):
            line = string.strip(line)
            if line[0] == '*':
                new_changelog.extend(['', line])
            elif line[0] == '-':
                new_changelog.append(line)
            else:
                new_changelog.append('  ' + line)

        # strip trailing newline inserted by first changelog entry
        if not new_changelog[0]:
            del new_changelog[0]

        return new_changelog

    # _format_changelog()

# class bdist_rpm 
Example 6
Project: ironpython2   Author: IronLanguages   File: pydoc.py    License: Apache License 2.0 6 votes vote down vote up
def source_synopsis(file):
    line = file.readline()
    while line[:1] == '#' or not strip(line):
        line = file.readline()
        if not line: break
    line = strip(line)
    if line[:4] == 'r"""': line = line[1:]
    if line[:3] == '"""':
        line = line[3:]
        if line[-1:] == '\\': line = line[:-1]
        while not strip(line):
            line = file.readline()
            if not line: break
        result = strip(split(line, '"""')[0])
    else: result = None
    return result 
Example 7
Project: ironpython2   Author: IronLanguages   File: pydoc.py    License: Apache License 2.0 6 votes vote down vote up
def help(self, request):
        if type(request) is type(''):
            request = request.strip()
            if request == 'help': self.intro()
            elif request == 'keywords': self.listkeywords()
            elif request == 'symbols': self.listsymbols()
            elif request == 'topics': self.listtopics()
            elif request == 'modules': self.listmodules()
            elif request[:8] == 'modules ':
                self.listmodules(split(request)[1])
            elif request in self.symbols: self.showsymbol(request)
            elif request in self.keywords: self.showtopic(request)
            elif request in self.topics: self.showtopic(request)
            elif request: doc(request, 'Help on %s:')
        elif isinstance(request, Helper): self()
        else: doc(request, 'Help on %s:')
        self.output.write('\n') 
Example 8
Project: Yuki-Chan-The-Auto-Pentest   Author: Yukinoshita47   File: Base.py    License: MIT License 6 votes vote down vote up
def ParseResolvConf(resolv_path):
    global defaults
    try:
        lines = open(resolv_path).readlines()
    except:
        print "error in path" + resolv_path
    for line in lines:
        line = string.strip(line)
        if not line or line[0] == ';' or line[0] == '#':
            continue
        fields = string.split(line)
        if len(fields) < 2:
            continue
        if fields[0] == 'domain' and len(fields) > 1:
            defaults['domain'] = fields[1]
        if fields[0] == 'search':
            pass
        if fields[0] == 'options':
            pass
        if fields[0] == 'sortlist':
            pass
        if fields[0] == 'nameserver':
            defaults['server'].append(fields[1]) 
Example 9
Project: service.subtitles.addic7ed   Author: cflannagan   File: service.py    License: GNU General Public License v2.0 6 votes vote down vote up
def search_filename(filename, languages):
  title, year = xbmc.getCleanMovieTitle(filename)
  log(__name__, "clean title: \"%s\" (%s)" % (title, year))
  try:
    yearval = int(year)
  except ValueError:
    yearval = 0
  if title and yearval > 1900:
    query_Film(title, year, item['3let_language'], filename)
  else:
    match = re.search(r'\WS(?P<season>\d\d)E(?P<episode>\d\d)', title, flags=re.IGNORECASE)
    if match is not None:
      tvshow = string.strip(title[:match.start('season')-1])
      season = string.lstrip(match.group('season'), '0')
      episode = string.lstrip(match.group('episode'), '0')
      query_TvShow(tvshow, season, episode, item['3let_language'], filename)
    else:
      search_manual(filename, item['3let_language'], filename) 
Example 10
Project: BinderFilter   Author: dxwu   File: bdist_rpm.py    License: MIT License 6 votes vote down vote up
def _format_changelog(self, changelog):
        """Format the changelog correctly and convert it to a list of strings
        """
        if not changelog:
            return changelog
        new_changelog = []
        for line in string.split(string.strip(changelog), '\n'):
            line = string.strip(line)
            if line[0] == '*':
                new_changelog.extend(['', line])
            elif line[0] == '-':
                new_changelog.append(line)
            else:
                new_changelog.append('  ' + line)

        # strip trailing newline inserted by first changelog entry
        if not new_changelog[0]:
            del new_changelog[0]

        return new_changelog

    # _format_changelog()

# class bdist_rpm 
Example 11
Project: BinderFilter   Author: dxwu   File: pydoc.py    License: MIT License 6 votes vote down vote up
def source_synopsis(file):
    line = file.readline()
    while line[:1] == '#' or not strip(line):
        line = file.readline()
        if not line: break
    line = strip(line)
    if line[:4] == 'r"""': line = line[1:]
    if line[:3] == '"""':
        line = line[3:]
        if line[-1:] == '\\': line = line[:-1]
        while not strip(line):
            line = file.readline()
            if not line: break
        result = strip(split(line, '"""')[0])
    else: result = None
    return result 
Example 12
Project: BinderFilter   Author: dxwu   File: platform.py    License: MIT License 6 votes vote down vote up
def _syscmd_uname(option,default=''):

    """ Interface to the system's uname command.
    """
    if sys.platform in ('dos','win32','win16','os2'):
        # XXX Others too ?
        return default
    try:
        f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
    except (AttributeError,os.error):
        return default
    output = string.strip(f.read())
    rc = f.close()
    if not output or rc:
        return default
    else:
        return output 
Example 13
Project: Computable   Author: ktraunmueller   File: bdist_rpm.py    License: MIT License 6 votes vote down vote up
def _format_changelog(self, changelog):
        """Format the changelog correctly and convert it to a list of strings
        """
        if not changelog:
            return changelog
        new_changelog = []
        for line in string.split(string.strip(changelog), '\n'):
            line = string.strip(line)
            if line[0] == '*':
                new_changelog.extend(['', line])
            elif line[0] == '-':
                new_changelog.append(line)
            else:
                new_changelog.append('  ' + line)

        # strip trailing newline inserted by first changelog entry
        if not new_changelog[0]:
            del new_changelog[0]

        return new_changelog

    # _format_changelog()

# class bdist_rpm 
Example 14
Project: Computable   Author: ktraunmueller   File: pydoc.py    License: MIT License 6 votes vote down vote up
def source_synopsis(file):
    line = file.readline()
    while line[:1] == '#' or not strip(line):
        line = file.readline()
        if not line: break
    line = strip(line)
    if line[:4] == 'r"""': line = line[1:]
    if line[:3] == '"""':
        line = line[3:]
        if line[-1:] == '\\': line = line[:-1]
        while not strip(line):
            line = file.readline()
            if not line: break
        result = strip(split(line, '"""')[0])
    else: result = None
    return result 
Example 15
Project: Computable   Author: ktraunmueller   File: platform.py    License: MIT License 6 votes vote down vote up
def _syscmd_uname(option,default=''):

    """ Interface to the system's uname command.
    """
    if sys.platform in ('dos','win32','win16','os2'):
        # XXX Others too ?
        return default
    try:
        f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
    except (AttributeError,os.error):
        return default
    output = string.strip(f.read())
    rc = f.close()
    if not output or rc:
        return default
    else:
        return output 
Example 16
Project: oss-ftp   Author: aliyun   File: bdist_rpm.py    License: MIT License 6 votes vote down vote up
def _format_changelog(self, changelog):
        """Format the changelog correctly and convert it to a list of strings
        """
        if not changelog:
            return changelog
        new_changelog = []
        for line in string.split(string.strip(changelog), '\n'):
            line = string.strip(line)
            if line[0] == '*':
                new_changelog.extend(['', line])
            elif line[0] == '-':
                new_changelog.append(line)
            else:
                new_changelog.append('  ' + line)

        # strip trailing newline inserted by first changelog entry
        if not new_changelog[0]:
            del new_changelog[0]

        return new_changelog

    # _format_changelog()

# class bdist_rpm 
Example 17
Project: oss-ftp   Author: aliyun   File: pydoc.py    License: MIT License 6 votes vote down vote up
def source_synopsis(file):
    line = file.readline()
    while line[:1] == '#' or not strip(line):
        line = file.readline()
        if not line: break
    line = strip(line)
    if line[:4] == 'r"""': line = line[1:]
    if line[:3] == '"""':
        line = line[3:]
        if line[-1:] == '\\': line = line[:-1]
        while not strip(line):
            line = file.readline()
            if not line: break
        result = strip(split(line, '"""')[0])
    else: result = None
    return result 
Example 18
Project: oss-ftp   Author: aliyun   File: platform.py    License: MIT License 6 votes vote down vote up
def _syscmd_uname(option,default=''):

    """ Interface to the system's uname command.
    """
    if sys.platform in ('dos','win32','win16','os2'):
        # XXX Others too ?
        return default
    try:
        f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
    except (AttributeError,os.error):
        return default
    output = string.strip(f.read())
    rc = f.close()
    if not output or rc:
        return default
    else:
        return output 
Example 19
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, pos, offset, line):
        "Initialize the synset from a line off a WN synset file."
	self.pos = pos
        "part of speech -- one of NOUN, VERB, ADJECTIVE, ADVERB."
	self.offset = offset
        """integer offset into the part-of-speech file.  Together
        with pos, this can be used as a unique id."""
	tokens = string.split(line[:string.index(line, '|')])
	self.ssType = tokens[2]
	self.gloss = string.strip(line[string.index(line, '|') + 1:])
        self.lexname = Lexname.lexnames[int(tokens[1])]
	(self._senseTuples, remainder) = _partition(tokens[4:], 2, string.atoi(tokens[3], 16))
	(self._pointerTuples, remainder) = _partition(remainder[1:], 4, int(remainder[0]))
	if pos == VERB:
	    (vfTuples, remainder) = _partition(remainder[1:], 3, int(remainder[0]))
	    def extractVerbFrames(index, vfTuples):
		return tuple(map(lambda t:string.atoi(t[1]), filter(lambda t,i=index:string.atoi(t[2],16) in (0, i), vfTuples)))
	    senseVerbFrames = []
	    for index in range(1, len(self._senseTuples) + 1):
		senseVerbFrames.append(extractVerbFrames(index, vfTuples))
	    self._senseVerbFrames = senseVerbFrames
	    self.verbFrames = tuple(extractVerbFrames(None, vfTuples))
            """A sequence of integers that index into
            VERB_FRAME_STRINGS. These list the verb frames that any
            Sense in this synset participates in.  (See also
            Sense.verbFrames.) Defined only for verbs.""" 
Example 20
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, pos, offset, line):
        "Initialize the synset from a line off a WN synset file."
	self.pos = pos
        "part of speech -- one of NOUN, VERB, ADJECTIVE, ADVERB."
	self.offset = offset
        """integer offset into the part-of-speech file.  Together
        with pos, this can be used as a unique id."""
	tokens = string.split(line[:string.index(line, '|')])
	self.ssType = tokens[2]
	self.gloss = string.strip(line[string.index(line, '|') + 1:])
        self.lexname = Lexname.lexnames[int(tokens[1])]
	(self._senseTuples, remainder) = _partition(tokens[4:], 2, string.atoi(tokens[3], 16))
	(self._pointerTuples, remainder) = _partition(remainder[1:], 4, int(remainder[0]))
	if pos == VERB:
	    (vfTuples, remainder) = _partition(remainder[1:], 3, int(remainder[0]))
	    def extractVerbFrames(index, vfTuples):
		return tuple(map(lambda t:string.atoi(t[1]), filter(lambda t,i=index:string.atoi(t[2],16) in (0, i), vfTuples)))
	    senseVerbFrames = []
	    for index in range(1, len(self._senseTuples) + 1):
		senseVerbFrames.append(extractVerbFrames(index, vfTuples))
	    self._senseVerbFrames = senseVerbFrames
	    self.verbFrames = tuple(extractVerbFrames(None, vfTuples))
            """A sequence of integers that index into
            VERB_FRAME_STRINGS. These list the verb frames that any
            Sense in this synset participates in.  (See also
            Sense.verbFrames.) Defined only for verbs.""" 
Example 21
Project: PythonClassBook   Author: PythonClassRoom   File: fig21_01.py    License: GNU General Public License v3.0 5 votes vote down vote up
def encrypt( self ):
      """Encrypt a text"""

      # get text from Text component
      text = self.text1.get( 1.0, END )
      text = string.strip( text )

      # encrypt text
      encryptedText = self.ciper.encrypt( text )
      self.text1.delete( 1.0, END )

      # display encrypted text
      self.text1.insert( END, encryptedText ) 
Example 22
Project: PythonClassBook   Author: PythonClassRoom   File: fig21_01.py    License: GNU General Public License v3.0 5 votes vote down vote up
def decrypt( self ):
      """Decrypt a text"""

      # get text from Text component
      text = self.text1.get( 1.0, END )
      text = string.strip( text )

      # decrypt text
      decryptedText = self.ciper.decrypt( text )
      self.text1.delete( 1.0, END )

      # display decrypted text
      self.text1.insert( END, decryptedText ) 
Example 23
Project: mishkal   Author: linuxscout   File: datetimeutil.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parse_timedelta(val):
    """
    returns a ``timedelta`` object, or None
    """
    if not val:
        return None
    val = string.lower(val)
    if "." in val:
        val = float(val)
        return timedelta(hours=int(val), minutes=60*(val % 1.0))
    fHour = ("h" in val or ":" in val)
    fMin  = ("m" in val or ":" in val)
    fFraction = "." in val
    for noise in "minu:teshour()":
        val = string.replace(val, noise, ' ')
    val = string.strip(val)
    val = string.split(val)
    hr = 0.0
    mi = 0
    val.reverse()
    if fHour:
        hr = int(val.pop())
    if fMin:
        mi = int(val.pop())
    if len(val) > 0 and not hr:
        hr = int(val.pop())
    return timedelta(hours=hr, minutes=mi) 
Example 24
Project: cf-mendix-buildpack   Author: mendix   File: munin.py    License: Apache License 2.0 5 votes vote down vote up
def print_requests_values(name, stats):
    print("multigraph mxruntime_requests_%s" % name)
    for sub, count in stats["requests"].items():
        substrip = "_" + string.strip(sub, "/").replace("-", "_")
        print("%s.value %s" % (substrip, count))
    print("") 
Example 25
Project: meddle   Author: glmcdona   File: pydoc.py    License: MIT License 5 votes vote down vote up
def splitdoc(doc):
    """Split a doc string into a synopsis line (if any) and the rest."""
    lines = split(strip(doc), '\n')
    if len(lines) == 1:
        return lines[0], ''
    elif len(lines) >= 2 and not rstrip(lines[1]):
        return lines[0], join(lines[2:], '\n')
    return '', join(lines, '\n') 
Example 26
Project: meddle   Author: glmcdona   File: pydoc.py    License: MIT License 5 votes vote down vote up
def interact(self):
        self.output.write('\n')
        while True:
            try:
                request = self.getline('help> ')
                if not request: break
            except (KeyboardInterrupt, EOFError):
                break
            request = strip(replace(request, '"', '', "'", ''))
            if lower(request) in ('q', 'quit'): break
            self.help(request) 
Example 27
Project: meddle   Author: glmcdona   File: pydoc.py    License: MIT License 5 votes vote down vote up
def showtopic(self, topic, more_xrefs=''):
        try:
            import pydoc_data.topics
        except ImportError:
            self.output.write('''
Sorry, topic and keyword documentation is not available because the
module "pydoc_data.topics" could not be found.
''')
            return
        target = self.topics.get(topic, self.keywords.get(topic))
        if not target:
            self.output.write('no documentation found for %s\n' % repr(topic))
            return
        if type(target) is type(''):
            return self.showtopic(target, more_xrefs)

        label, xrefs = target
        try:
            doc = pydoc_data.topics.topics[label]
        except KeyError:
            self.output.write('no documentation found for %s\n' % repr(topic))
            return
        pager(strip(doc) + '\n')
        if more_xrefs:
            xrefs = (xrefs or '') + ' ' + more_xrefs
        if xrefs:
            import StringIO, formatter
            buffer = StringIO.StringIO()
            formatter.DumbWriter(buffer).send_flowing_data(
                'Related help topics: ' + join(split(xrefs), ', ') + '\n')
            self.output.write('\n%s\n' % buffer.getvalue()) 
Example 28
Project: meddle   Author: glmcdona   File: platform.py    License: MIT License 5 votes vote down vote up
def _parse_release_file(firstline):

    # Default to empty 'version' and 'id' strings.  Both defaults are used
    # when 'firstline' is empty.  'id' defaults to empty when an id can not
    # be deduced.
    version = ''
    id = ''

    # Parse the first line
    m = _lsb_release_version.match(firstline)
    if m is not None:
        # LSB format: "distro release x.x (codename)"
        return tuple(m.groups())

    # Pre-LSB format: "distro x.x (codename)"
    m = _release_version.match(firstline)
    if m is not None:
        return tuple(m.groups())

    # Unkown format... take the first two words
    l = string.split(string.strip(firstline))
    if l:
        version = l[0]
        if len(l) > 1:
            id = l[1]
    return '', version, id 
Example 29
Project: meddle   Author: glmcdona   File: platform.py    License: 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 30
Project: meddle   Author: glmcdona   File: xmlrpclib.py    License: MIT License 5 votes vote down vote up
def decode(self, data):
        data = str(data)
        self.value = string.strip(data)