• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python textwrap.wrap函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中textwrap.wrap函数的典型用法代码示例。如果您正苦于以下问题:Python wrap函数的具体用法?Python wrap怎么用?Python wrap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了wrap函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: formatDocumentation

    def formatDocumentation(self, node, indent=''):
        """Generate a Python docstring from a Node.

        The returned value includes quotes begin and end double-quotes. 
        Multi-line documentation will be wrapped and combined with raw '\n' characters as
        separators (so newlines will be interpreted by the C++ compiler not the code generator).
        """
        lines = []
        if node.brief:
            for item in node.brief:
                if hasattr(item, "tag"):
                    lines.extend(self.formatCode(item))
                else:
                    lines.extend(textwrap.wrap(item, width=settings.docwidth))
                lines.append("")
        if hasattr(node, "params") and node.params:
            name_width = 0
            for param in node.params:
                if param.name and param.brief and len(param.name) > name_width:
                    name_width = len(param.name)
            if name_width > 0:
                lines.append("Arguments:")
                wrapper = textwrap.TextWrapper(
                    initial_indent="  ",
                    subsequent_indent=(" " * (name_width + 5)),
                    width=settings.docwidth
                    )
                for param in node.params:
                    if not param.name or len(param.name) == 0: continue
                    sep = "-" * (name_width + 1 - len(param.name))
                    if param.brief:
                        lines.extend(
                            wrapper.wrap(
                                "{name} {sep} {descr}".format(
                                    name=param.name, sep=sep, descr=param.brief[0])
                                )
                            )
                    if len(param.brief) > 1:
                        for item in param.brief[1:]:
                            if hasattr(item, "tag"):
                                lines.extend(self.formatCode(item))
                            else:
                                lines.extend(textwrap.wrap(item, width=settings.docwidth))
                lines.append("")
        if node.detailed:
            for item in node.detailed:
                if hasattr(item, "tag"):
                    lines.extend(self.formatCode(item))
                else:
                    lines.extend(textwrap.wrap(item, width=settings.docwidth))
                lines.append("")
        if not lines:
            return '""'
        lines = [line.replace('\\', r'\\') for line in lines]
        lines = [line.replace('"', r'\"') for line in lines]
        template = '{indent}"{line}\\n"'
        return "\n".join(
            [template.format(indent="", line=lines[0])] 
            + [template.format(indent=indent, line=line) for line in lines[1:]]
            )
开发者ID:lsst-dm,项目名称:bp,代码行数:60,代码来源:processor.py


示例2: format_private_key

    def format_private_key(key, heads=True):
        """
        Returns a private key (adding header & footer if required).

        :param key A private key
        :type: string

        :param heads: True if we want to include head and footer
        :type: boolean

        :returns: Formated private key
        :rtype: string
        """
        private_key = key.replace('\x0D', '')
        private_key = private_key.replace('\r', '')
        private_key = private_key.replace('\n', '')
        if len(private_key) > 0:
            if private_key.find('-----BEGIN PRIVATE KEY-----') != -1:
                private_key = private_key.replace('-----BEGIN PRIVATE KEY-----', '')
                private_key = private_key.replace('-----END PRIVATE KEY-----', '')
                private_key = private_key.replace(' ', '')
                if heads:
                    private_key = "-----BEGIN PRIVATE KEY-----\n" + "\n".join(wrap(private_key, 64)) + "\n-----END PRIVATE KEY-----\n"
            else:
                private_key = private_key.replace('-----BEGIN RSA PRIVATE KEY-----', '')
                private_key = private_key.replace('-----END RSA PRIVATE KEY-----', '')
                private_key = private_key.replace(' ', '')
                if heads:
                    private_key = "-----BEGIN RSA PRIVATE KEY-----\n" + "\n".join(wrap(private_key, 64)) + "\n-----END RSA PRIVATE KEY-----\n"
        return private_key
开发者ID:foxwill,项目名称:python-saml,代码行数:30,代码来源:utils.py


示例3: _CheckAndHandleCredentialException

def _CheckAndHandleCredentialException(e, args):
  # Provide detail to users who have no boto config file (who might previously
  # have been using gsutil only for accessing publicly readable buckets and
  # objects).
  # pylint: disable=g-import-not-at-top
  from gslib.util import HasConfiguredCredentials
  if (not HasConfiguredCredentials() and
      not boto.config.get_value('Tests', 'bypass_anonymous_access_warning',
                                False)):
    # The check above allows tests to assert that we get a particular,
    # expected failure, rather than always encountering this error message
    # when there are no configured credentials. This allows tests to
    # simulate a second user without permissions, without actually requiring
    # two separate configured users.
    _OutputAndExit('\n'.join(textwrap.wrap(
        'You are attempting to access protected data with no configured '
        'credentials. Please visit '
        'https://cloud.google.com/console#/project and sign up for an '
        'account, and then run the "gsutil config" command to configure '
        'gsutil to use these credentials.')))
  elif (e.reason and
        (e.reason == 'AccountProblem' or e.reason == 'Account disabled.' or
         'account for the specified project has been disabled' in e.reason)
        and ','.join(args).find('gs://') != -1):
    _OutputAndExit('\n'.join(textwrap.wrap(
        _ConstructAccountProblemHelp(e.reason))))
开发者ID:fedmich,项目名称:gsutil,代码行数:26,代码来源:__main__.py


示例4: wrap_columns

def wrap_columns(col1, col2, width1=24, width2=40, indent=31):
    """
    Takes two strings of text and turns them into nicely formatted column output.

    Used by display_module()
    """
    
    lines1 = textwrap.wrap(textwrap.dedent(col1).strip(), width=width1)
    lines2 = textwrap.wrap(textwrap.dedent(col2).strip(), width=width2)

    result = ''

    limit = max(len(lines1), len(lines2))

    for x in xrange(limit):

        if x < len(lines1):
            if x != 0:
                result +=  ' '*indent
            result += '{line: <0{width}s}'.format(width=width1, line=lines1[x])
        else:
            if x == 0:
                result += ' '*width1
            else:
                result += ' '*(indent + width1)

        if x < len(lines2):
            result +=  '  ' + '{line: <0{width}s}'.format(width=width2, line=lines2[x])

        if x != limit-1:
            result += "\n"

    return result
开发者ID:52piaoyu,项目名称:Empire,代码行数:33,代码来源:messages.py


示例5: formatMessage

    def formatMessage(msgline, width=70):
        """Format a long single line message so that it is easier to read.

        msgline is a string containing a single message. It can either be
        a plain message string which is reformatted using the textwrap
        module or it can be of the form <decl>;<msg> where <decl> is the
        declaration string and <msg> an arbitrary message. Lines of this
        form will be separated so that the declaration and the message
        appear in individual text blocks, where every line of message will start
        with '>' character.

        width is the maximum width of any text blocks (without indendation).
        """
        txts = msgline.split(";")
        # Ensure that there are no more than two items in txts
        if len( txts ) != 2:
            #If message is not in format we expected, just return it
            return os.linesep.join( textwrap.wrap( msgline, width ) )
            
        lines = [ txts[0] ] #I don't want to break declaration string to few lines
        
        # Insert a separator if there are two parts (=decl and msg)
        # Apply the text wrapper to shorten the maximum line length
        wrapped_lines = textwrap.wrap( txts[1], width )
        lines.extend( map( lambda s: "> " + s.strip(), wrapped_lines ) )
        
        return os.linesep.join(lines)
开发者ID:BackupTheBerlios,项目名称:slon,代码行数:27,代码来源:multi_line_formatter.py


示例6: __init__

	def __init__(self, prog='', description=None, epilog=None):
		self.prog = prog
		self.description = '\n'.join(textwrap.wrap((description or ''), MAX_WIDTH))
		self.epilog = '\n'.join(textwrap.wrap((epilog or ''), MAX_WIDTH))
		self.__arguments__ = {}
		self.__positionals__ = []
		self.ignore_urls = True
开发者ID:jamcut,项目名称:cassie-bot,代码行数:7,代码来源:argparselite.py


示例7: __get_docstr

def __get_docstr(text, indent=0):
    """ Format a docstring. Take the first sentence (. followed by a space)
        and use it for the brief. Then put the rest of the text after a blank
        line if there is text there
    """
    text = text.strip().encode("utf-8")
    dotpos = text.find(". ")
    if dotpos > 0:
        brief = text[:dotpos+1]
        content = text[dotpos+2:]
    else:
        brief = text
        content = ""
    if indent == 0:
        istr = ""
    else:
        istr = "{0:{1}}".format(" ", indent)
    
    brief = "\n{0} *  ".format(istr).join(textwrap.wrap(brief, 80))
    content = "\n{0} *  ".format(istr).join(textwrap.wrap(content, 80))
    docstr = "{0}/** \\brief {1}".format(istr, brief)
    if len(content) > 0:
        docstr += "\n{0} * \n{0} *  {1}".format(istr, content)
    docstr += "\n{0} */".format(istr)
    return docstr
开发者ID:lpugin,项目名称:libmei,代码行数:25,代码来源:cplusplus.py


示例8: create_image

def create_image(message, user, location):

	font = ImageFont.truetype(os.path.join(font_path, Font), int(font_size))
	margin = offset = 20

	if watermark_logo:
		wrap = textwrap.wrap(message,width=50)
	else:
		# No logo then make the lines a bit wider
		wrap = textwrap.wrap(message,width=55)

	line_height = font.getsize(wrap[0])[1]
	print "line height: " + str(line_height)
	print wrap

	# Make the image double the size to start with, so that we can apply a anti-alias function when we scale down. Text looks better (I think)
	# enough space for "margin" at the top and bottom and also a .5 margin between the comment and the attribution
	img=Image.new("RGBA", (900,int(2.5*margin+line_height*(len(wrap)+1))),(background_color))
	draw = ImageDraw.Draw(img)
	wrap_text(wrap,font,draw)
	draw.text((margin,int(1.5*margin+line_height*len(wrap))), u" \u2014 "  + user + ", " + location,font=font,fill=font_color)

	if watermark_logo:
		# If there's a logo file provided then make space for it and paste it into the upper right corner.
		logo = Image.open(watermark_logo)
		box = (800, 0, 900, 100)
		img.paste(logo, box)

	img_resized = img.resize((450, int(2.5*.5*margin+(line_height * .5)*(len(wrap)+1))), Image.ANTIALIAS)
	draw = ImageDraw.Draw(img_resized)
	img_resized.save("test_tweet_reply.png")
开发者ID:comp-journalism,项目名称:Comment-Bot,代码行数:31,代码来源:test_imageModule.py


示例9: format_bundle_info

def format_bundle_info(log, descriptor):
    """
    Formats a release notes summary output for an app, engine or core
    """
    
    # yay we can install! - get release notes
    (summary, url) = descriptor.get_changelog()
    if summary is None:
        summary = "No details provided."
    
    
    log.info("/%s" % ("-" * 70))
    log.info("| Item:        %s" % descriptor)
    log.info("|")
    
    str_to_wrap = "Description: %s" % descriptor.get_description()
    for x in textwrap.wrap(str_to_wrap, width=68, initial_indent="| ", subsequent_indent="|              "):
        log.info(x)
    log.info("|")
    
    str_to_wrap = "Change Log:  %s" % summary
    for x in textwrap.wrap(str_to_wrap, width=68, initial_indent="| ", subsequent_indent="|              "):
        log.info(x)
    
    log.info("\%s" % ("-" * 70))
开发者ID:bdeluca,项目名称:tk-core,代码行数:25,代码来源:console_utils.py


示例10: save_fig

def save_fig(y, summary_index, total_matrix, gene_matrix, t, ARS, plottitle, filetitle, tumor_name):


	df_high, df_low, total_number = divide_into_two(gene_matrix, total_matrix, t)
	
	fig = plt.figure()
	fig.suptitle("\n".join(wrap(('Expression of ' + str(ARS) + ' in ' + tumor_name))), fontsize = 13)
	if (y == "TCGA-CESC") or (y == "TCGA-DLBC"):
		fig.subplots_adjust(top = 0.80)
	else:
		fig.subplots_adjust(top = 0.85)
	ax = plt.subplot(111)
	ax.set_title("\n".join(wrap(plottitle)), fontsize = 11)
	plt.ylim(0, 1)
	p_value, hm5, hm10, lm5, lm10 = kmplot(df_high, df_low, ax)
	favorable5y = survival_compare(hm5, lm5)
	favorable10y = survival_compare(hm10, lm10)
	df = pd.DataFrame()
	rows = []
	rows.append([ARS, plottitle, total_number, favorable5y, favorable10y, p_value])
	df = pd.DataFrame(rows, columns = cols)
	summary_index = summary_index.append(df)
	fig.savefig('X:\\Su Lab\\TCGA\\Data\\Plot\\' + y + "\\" + ARS + "\\" + y + '-' + ARS + '-' + filetitle + '.png')
	plt.close("all")
	return(summary_index)
开发者ID:yuwtsri,项目名称:tcga-script,代码行数:25,代码来源:Gene_expression_plot_each.py


示例11: render_article

def render_article(term, html_text):
    """ Render and return html text of article as text. """
    html_renderer = html2text.HTML2Text(bodywidth=term.width - 1)
    html_renderer.ignore_links = True
    html_renderer.ignore_images = True

    text_wrapped = []
    for line in html_renderer.handle(html_text).splitlines():
        if len(line) < term.width:
            text_wrapped.append(line)
        else:
            # html2text does not always honor `bodywidth',
            # calculate indentation (line up with previous indent)
            # and textwrap again.
            _subsq_indent = 0
            for _subsq_indent, char in enumerate(line):
                if not char.isspace():
                    break
            _indent = u' ' * _subsq_indent
            text_wrapped.extend(textwrap.wrap(line, term.width - 1,
                                              subsequent_indent=_indent))
    final = [_text.rstrip() for _text in text_wrapped]

    if not final or not any(_line for _line in final):
        # no text was rendered by html2text
        final = [''] * (term.height // 2)
        final.extend(textwrap.wrap(MSG_NOTEXT, term.width - 1))
    return final
开发者ID:tehmaze,项目名称:x84,代码行数:28,代码来源:hackernews.py


示例12: test_encoding_detection

def test_encoding_detection(file_name, encoding):
    with open(file_name, 'rb') as f:
        input_bytes = f.read()
        result = chardet.detect(input_bytes)
        try:
            expected_unicode = input_bytes.decode(encoding)
        except LookupError:
            expected_unicode = ''
        try:
            detected_unicode = input_bytes.decode(result['encoding'])
        except (LookupError, UnicodeDecodeError, TypeError):
            detected_unicode = ''
    if result:
        encoding_match = (result['encoding'] or '').lower() == encoding
    else:
        encoding_match = False
    # Only care about mismatches that would actually result in different
    # behavior when decoding
    if not encoding_match and expected_unicode != detected_unicode:
        wrapped_expected = '\n'.join(textwrap.wrap(expected_unicode, 100)) + '\n'
        wrapped_detected = '\n'.join(textwrap.wrap(detected_unicode, 100)) + '\n'
        diff = ''.join(ndiff(wrapped_expected.splitlines(True),
                             wrapped_detected.splitlines(True)))
    else:
        diff = ''
        encoding_match = True
    assert encoding_match, ("Expected %s, but got %s for %s.  Character "
                            "differences: \n%s" % (encoding,
                                                   result,
                                                   file_name,
                                                   diff))
开发者ID:Perkville,项目名称:chardet,代码行数:31,代码来源:test.py


示例13: _get_trait_desc

    def _get_trait_desc(self, inputs, name, spec):
        desc = spec.desc
        xor = spec.xor
        requires = spec.requires

        manhelpstr = ['\t%s' % name]
        try:
            setattr(inputs, name, None)
        except TraitError as excp:
            def_val = ''
            if getattr(spec, 'usedefault'):
                def_val = ', nipype default value: %s' % str(getattr(spec, 'default_value')()[1])
            line = "(%s%s)" % (excp.info, def_val)
            manhelpstr = wrap(line, 90, initial_indent=manhelpstr[0]+': ',
                              subsequent_indent='\t\t ')
        if desc:
            for line in desc.split('\n'):
                manhelpstr += wrap(line, 90, initial_indent='\t\t',
                                   subsequent_indent='\t\t')
        if xor:
            line = '%s' % ', '.join(xor)
            manhelpstr += wrap(line, 90, initial_indent='\t\tmutually_exclusive: ',
                               subsequent_indent='\t\t ')
        if requires: # and name not in xor_done:
            others = [field for field in requires if field != name]
            line = '%s' % ', '.join(others)
            manhelpstr += wrap(line, 90, initial_indent='\t\trequires: ',
                               subsequent_indent='\t\t ')
        return manhelpstr
开发者ID:czarrar,项目名称:nipype,代码行数:29,代码来源:base.py


示例14: hanging_indent

def hanging_indent(text, intro, termwidth=None, change_spaces=True,
                   introwidth=None):
    """Produce text with a hanging indent.

    .. versionadded:: 3.3.0
    .. versionchanged:: 4.0.0
    """
    if termwidth is None:
        termwidth = get_termwidth() or 9001
    if introwidth is None:
        introwidth = len(intro)
    nowrap = intro + text
    if intro:
        wrapv = textwrap.wrap(nowrap, termwidth,
                              break_on_hyphens=False)
    else:
        wrapv = textwrap.wrap(nowrap, termwidth - introwidth,
                              break_on_hyphens=False)
    wrap0 = wrapv[0]
    wraprest = textwrap.wrap('\n'.join(wrapv[1:]), termwidth -
                             introwidth,
                             break_on_hyphens=False)
    if change_spaces:
        wraprest = [i.replace('  ', ' ').replace(' ', '  ') for i
                    in wraprest]
    buf = wrap0
    for i in wraprest:
        buf += '\n' + introwidth * ' ' + i

    return buf
开发者ID:cajone,项目名称:pkgbuilder,代码行数:30,代码来源:ui.py


示例15: showPlugins

    def showPlugins(self):
        """Print list of available plugins.
        """
        import textwrap

        class DummyParser:
            def __init__(self):
                self.options = []
            def add_option(self, *arg, **kw):
                self.options.append((arg, kw.pop('help', '')))
        
        v = self.config.verbosity
        self.config.plugins.sort()
        for p in self.config.plugins:            
            print "Plugin %s" % p.name
            if v >= 2:
                print "  score: %s" % p.score
                print '\n'.join(textwrap.wrap(p.help().strip(),
                                              initial_indent='  ',
                                              subsequent_indent='  '))
                if v >= 3:
                    print
                    print "  Options:"
                    parser = DummyParser()
                    p.addOptions(parser)
                    for opts, help in parser.options:
                        print '  %s' % (', '.join(opts))
                        if help:
                            print '\n'.join(
                                textwrap.wrap(help.strip(),
                                              initial_indent='    ',
                                              subsequent_indent='    '))
                print
开发者ID:antlong,项目名称:nose,代码行数:33,代码来源:core.py


示例16: print_defines

def print_defines():
	'''Print the #defines for the wiredtiger.in file.'''
	f.write('''
/*!
 * @name Connection statistics
 * @anchor statistics_keys
 * @anchor statistics_conn
 * Statistics are accessed through cursors with \c "statistics:" URIs.
 * Individual statistics can be queried through the cursor using the following
 * keys.  See @ref data_statistics for more information.
 * @{
 */
''')
	for v, l in enumerate(connection_stats):
		f.write('/*! %s */\n' % '\n * '.join(textwrap.wrap(l.desc, 70)))
		f.write('#define\tWT_STAT_CONN_' + l.name.upper() + "\t" *
		    max(1, 6 - int((len('WT_STAT_CONN_' + l.name)) / 8)) +
		    str(v) + '\n')
	f.write('''
/*!
 * @}
 * @name Statistics for data sources
 * @anchor statistics_dsrc
 * @{
 */
''')
	for v, l in enumerate(dsrc_stats):
		f.write('/*! %s */\n' % '\n * '.join(textwrap.wrap(l.desc, 70)))
		f.write('#define\tWT_STAT_DSRC_' + l.name.upper() + "\t" *
		    max(1, 6 - int((len('WT_STAT_DSRC_' + l.name)) / 8)) +
		    str(v) + '\n')
	f.write('/*! @} */\n')
开发者ID:niumowm,项目名称:wiredtiger,代码行数:32,代码来源:stat.py


示例17: _splitit

    def _splitit(self, line, isheader):
        """Split each element of line to fit the column width

        Each element is turned into a list, result of the wrapping of the
        string to the desired width
        """

        line_wrapped = []
        for cell, width in zip(line, self._width):
            array = []
            original_cell = cell
            lost_color = bcolors.WHITE
            for attr in bcolors_public_props():
                cell = cell.replace(
                    getattr(bcolors, attr), '').replace(bcolors.ENDC,'')
                if cell.replace(bcolors.ENDC,'') != original_cell.replace(
                        bcolors.ENDC,'') and attr != 'ENDC':
                    if not lost_color:
                        lost_color = attr
            for c in cell.split('\n'):
                try:
                    c = unicode(c, 'utf')
                except UnicodeDecodeError, strerror:
                    sys.stderr.write("UnicodeDecodeError exception for string '%s': %s\n" % (c, strerror))
                    c = unicode(c, 'utf', 'replace')
                try:
                    array.extend(
                        [get_color_string(
                            getattr(bcolors, lost_color),x
                            ) for x in  textwrap.wrap(c, width)
                        ]
                    )
                except AttributeError:
                    array.extend(textwrap.wrap(c, width))
            line_wrapped.append(array)
开发者ID:spacelis,项目名称:python-texttable,代码行数:35,代码来源:texttable.py


示例18: format_command_help

def format_command_help(command_list):

    row_list = _command_list_to_table_cells(command_list)
    lines = []
    for row_cells in row_list:
        if len(row_cells) == 1:
            heading = row_cells[0]
            lines.append('')
            lines.append(bold(heading))
            lines.append('')
        elif len(row_cells) == 2:
            cell1, cell2 = row_cells
    
            cell1_lines = textwrap.wrap(cell1, WIDTH, subsequent_indent='    ')
            cell2_lines = textwrap.wrap(cell2, 79 - INDENT - 3 - WIDTH)
            
            first_line = True
            while cell1_lines or cell2_lines:
                line = ' ' * INDENT
                if cell1_lines:
                    line += cell1_lines.pop(0).ljust(WIDTH)
                else:
                    line += ' ' * (WIDTH)
                line += ' : ' if first_line else '   '
                if cell2_lines:
                    line += cell2_lines.pop(0)
                lines.append(line)
                first_line = False

    return '\n'.join(lines)
开发者ID:robwalton,项目名称:diffcalc,代码行数:30,代码来源:help.py


示例19: draw_book_title

def  draw_book_title(file_path, book_title):

    import PIL
    from PIL import ImageFont
    from PIL import Image
    from PIL import ImageDraw
    import textwrap
    
    img=Image.open(file_path)
    draw = ImageDraw.Draw(img)
    
    offset = 315
    margin = 41
    
    wrapped_text = textwrap.wrap(book_title, width=12, break_long_words=False, break_on_hyphens=False)
    if len(wrapped_text)>3:
        wrapped_text = textwrap.wrap(book_title, width=16, break_long_words=False, break_on_hyphens=False)
        font_size = 69
    else:
        font_size = 81
    
    
    font = ImageFont.truetype("/Library/Fonts/Arial Narrow Bold.ttf", font_size)

    for line in wrapped_text:
        draw.text((margin, offset), line, font=font)
        offset += font.getsize(line)[1]
    
    img.save(file_path)
开发者ID:Mondego,项目名称:pyreco,代码行数:29,代码来源:allPythonContent.py


示例20: format_commands_for_rst_table

def format_commands_for_rst_table(title, command_list):
    W1 = WIDTH  # internal width
    W2 = 79 - W1 - 3  # internal width
    HORIZ_LINE = '+-' + '-' * W1 + '-+-' + '-' * W2 + '-+'
    
    row_list = _command_list_to_table_cells(command_list)
    
    lines = []
  
    lines.append(HORIZ_LINE)  # Top line
    for row_cells in row_list:
        if len(row_cells) == 1:
            lines.append('| ' + ('**' + row_cells[0] + '**').ljust(W1 + W2 + 3) + ' |')
        
        elif len(row_cells) == 2:
            cmd_and_args = row_cells[0].split(' ', 1)
            cmd = cmd_and_args[0]
            args = cmd_and_args[1] if len(cmd_and_args) == 2 else ''
            cell1 = '**-- %s** %s' % (cmd, args)
            cell1_lines = textwrap.wrap(cell1, W1)  #, subsequent_indent='    ')
            cell2_lines = textwrap.wrap(row_cells[1], W2)
            
            while cell1_lines or cell2_lines:
                line = '| '
                line += (cell1_lines.pop(0) if cell1_lines else '').ljust(W1)
                line += ' | '
                line += (cell2_lines.pop(0) if cell2_lines else '').ljust(W2)
                line += ' |'
                lines.append(line)
        
        else:
            assert False
        
        lines.append(HORIZ_LINE)
    return lines
开发者ID:robwalton,项目名称:diffcalc,代码行数:35,代码来源:help.py



注:本文中的textwrap.wrap函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python textwrap.TextWrapper类代码示例发布时间:2022-05-27
下一篇:
Python textwrap.indent函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap