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

Python nine.str函数代码示例

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

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



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

示例1: reorder_po

def reorder_po(path, encoding='utf-8'):
    p = Path(path)
    if p.is_dir():
        for path in p.glob('**.po'):
            _reorder_one(str(path), encoding=encoding)
    else:
        _reorder_one(str(path), encoding=encoding)
开发者ID:dmckeone,项目名称:bag,代码行数:7,代码来源:reorder_po.py


示例2: test_raise_plus_with_an_operand

 def test_raise_plus_with_an_operand(self):
     try:
         XMLTemplate('<x>${"ciao" + }</x>')
         assert False, 'must raise'
     except XMLTemplateCompileError as e:
         assert 'detected an invalid python expression' in str(e), e
         assert '"ciao" +' in str(e), e
开发者ID:nandoflorestan,项目名称:kajiki,代码行数:7,代码来源:test_xml.py


示例3: find_dups

def find_dups(directory='.', files='*.jpg', callbacks=[]):
    '''Given a ``directory``, goes through all files that pass through the
        filter ``files``, and for each one that is a duplicate, calls a number
        of ``callbacks``. Returns a dictionary containing the duplicates found.

        Example usage::

            d = find_dups('some/directory',
                          callbacks=[print_dups, KeepLarger()])

        The signature for writing callbacks is (existing, dup, m), where
        ``existing`` and ``dup`` are paths and ``m`` is the
        FileExistenceManager instance.
        '''
    from pathlib import Path
    store = GdbmStorageStrategy()
    m = FileExistenceManager(store)
    dups = {}
    for p in Path(directory).glob(files):
        with open(str(p), 'rb') as stream:
            existing = m.try_add_file(stream, str(p))
        if existing:
            existing = existing.decode('utf-8')
            dups[str(p)] = existing
            for function in callbacks:
                function(Path(existing), p, m)
    m.close()
    return dups
开发者ID:dmckeone,项目名称:bag,代码行数:28,代码来源:file_existence_manager.py


示例4: test_expr_multiline_and_IndentationError

 def test_expr_multiline_and_IndentationError(self):
     try:
         XMLTemplate("""<div>Hello, ${ 'pippo' +
             'baudo'}</div>""")().render()
     except XMLTemplateCompileError as e:
         assert "`'pippo' +\n                'baudo'`" in str(e), str(e)
         assert 'Hello' in str(e)
         assert 'baudo' in str(e)
开发者ID:nandoflorestan,项目名称:kajiki,代码行数:8,代码来源:test_xml.py


示例5: _collect

 def _collect(self, it):
     result = []
     for part in it:
         if part is None:
             continue
         if isinstance(part, flattener):
             result.append(str(part.accumulate_str()))
         else:
             result.append(str(part))
     if result:
         return ''.join(result)
     else:
         return None
开发者ID:nandoflorestan,项目名称:kajiki,代码行数:13,代码来源:template.py


示例6: pick_one_of

def pick_one_of(options, prompt='Pick one: '):
    '''Lets the user pick an item by number.'''
    alist = options if isinstance(options, list) else list(options)
    c = 0
    for o in alist:
        c += 1
        print(str(c).rjust(2) + ". " + str(o))
    while True:
        try:
            opt = int(input(prompt))
        except ValueError:
            continue
        return alist[opt - 1]
开发者ID:chronossc,项目名称:bag,代码行数:13,代码来源:console.py


示例7: test_dtd

 def test_dtd(self):
     dtd = DocumentTypeDeclaration.by_uri['']
     assert dtd.name == 'html5'
     assert str(dtd) == '<!DOCTYPE html>', str(dtd)
     assert dtd.rendering_mode == 'html5'
     dtd = DocumentTypeDeclaration.by_uri[None]
     assert dtd.name == 'xhtml5'
     assert str(dtd) == '<!DOCTYPE html>', str(dtd)
     assert dtd.rendering_mode == 'xml'
     dtd = DocumentTypeDeclaration.by_uri[
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"]
     assert dtd.name == 'xhtml1transitional'
     assert str(dtd) == XHTML1
     assert dtd.rendering_mode == 'xml'
开发者ID:drocco007,项目名称:kajiki,代码行数:14,代码来源:test_doctype.py


示例8: test_raise_unclosed_string

 def test_raise_unclosed_string(self):
     try:
         XMLTemplate('<x>${"ciao}</x>')
         assert False, 'must raise'
     except XMLTemplateCompileError as e:
         # assert "can't compile" in str(e), e  # different between pypy and cpython
         assert '"ciao' in str(e), e
开发者ID:nandoflorestan,项目名称:kajiki,代码行数:7,代码来源:test_xml.py


示例9: test_only_comment

 def test_only_comment(self):
     try:
         XMLTemplate('<!-- a -->')
     except XMLTemplateParseError as e:
         assert 'no element found' in str(e), e
     else:
         assert False, 'should have raised'
开发者ID:nandoflorestan,项目名称:kajiki,代码行数:7,代码来源:test_xml.py


示例10: test_multiple_nodes

 def test_multiple_nodes(self):
     try:
         XMLTemplate('<!-- a --><x>${1+1}</x><y>${1+1}</y>')
     except XMLTemplateParseError as e:
         assert 'junk after document element' in str(e), e
     else:
         assert False, 'should have raised'
开发者ID:nandoflorestan,项目名称:kajiki,代码行数:7,代码来源:test_xml.py


示例11: output

 def output(self, encoding='utf-8'):
     '''Returns the final Python code with the fixture functions.'''
     return TEMPLATE.format(
         encoding=encoding, when=str(datetime.utcnow())[:16],
         imports='\n'.join(self.imports), pk=self.pk,
         the_fixtures='\n'.join(self.lines),
         )
开发者ID:erickwilder,项目名称:bag,代码行数:7,代码来源:mediovaigel.py


示例12: __iter__

 def __iter__(self):
     """We convert the chunk to string because it can be of any type
     -- after all, the template supports expressions such as ${x+y}.
     Here, ``chunk`` can be the computed expression result.
     """
     for chunk in self.__main__():
         yield str(chunk)
开发者ID:nandoflorestan,项目名称:kajiki,代码行数:7,代码来源:template.py


示例13: test_request2

 def test_request2(self):
     deps = self.PageDeps()
     deps.lib('jquery.ui')
     deps.lib('jquery.ui')  # requiring twice should have no effect
     SCRIPTS_OUT = '<script type="text/javascript" ' \
         'src="/static/lib/jquery-1.7.1.min.js"></script>\n' \
         '<script type="text/javascript" ' \
         'src="/static/lib/jquery-ui-1.8.16.min.js"></script>'
     self.assertEqual(deps.lib.tags, SCRIPTS_OUT)
     deps.css('deform')
     CSS_OUT = '<link rel="stylesheet" ' \
         'type="text/css" href="http://jquery.css" />\n' \
         '<link rel="stylesheet" type="text/css" '\
         'href="http://jquery.ui.css" />\n' \
         '<link rel="stylesheet" type="text/css" ' \
         'href="http://deform.css" />'
     self.assertEqual(deps.css.tags, CSS_OUT)
     ALERT = 'alert("Bruhaha");'
     deps.script(ALERT)
     deps.script(ALERT)  # Repeating should have no effect
     ALERT_OUT = '<script type="text/javascript">' \
         '\nalert("Bruhaha");\n</script>\n'
     self.assertEqual(deps.script.tags, ALERT_OUT)
     self.assertEqual(deps.top_output, CSS_OUT)
     self.assertEqual(deps.bottom_output, SCRIPTS_OUT + '\n' + ALERT_OUT)
     self.assertEqual(str(deps), '\n'.join([
         CSS_OUT, SCRIPTS_OUT, ALERT_OUT]))
开发者ID:dmckeone,项目名称:bag,代码行数:27,代码来源:test_web_deps.py


示例14: regex_validator

def regex_validator(node, value):
    '''Validator that ensures a regular expression can be compiled.'''
    try:
        re.compile(value)
    except Exception as e:
        raise c.Invalid(node, _("Invalid regular expression: {}")
            .format(str(e)))
开发者ID:Rafails,项目名称:MyCalc,代码行数:7,代码来源:schema.py


示例15: excel_reader

def excel_reader(stream, worksheet_name=None, required_headers=[]):
    '''Reads an XLSX file (from ``stream``) and yields objects so you can
        access the values conveniently.

        You can pass in the ``worksheet_name`` to be read.  If not passed in or
        not present in the file, the first worksheet will be read.

        In addition, you may pass a sequence of *required_headers*, and if they
        aren't all present, KeyError is raised.

        Let's see an example. Suppose you are reading some Excel file and
        all you know is it contains the columns "E-mail", "Full Name" and
        "Gender", not necessarily in that order::

            reader = excel_reader(
                open('contacts.xlsx', mode='rb'),
                worksheet_name='Mailing',
                required_headers=['E-mail', 'Full Name', 'Gender'])
            for o in reader:
                print(o.full_name, o.e_mail, o.gender)
        '''
    try:
        wb = load_workbook(stream, data_only=True)
    except (BadZipFile, InvalidFileException) as e:
        raise Problem(
            _('That is not an XLSX file.'),
            error_title=_('Unable to read the XLSX file'), error_debug=str(e))

    # Grab either the worksheet named "Assets", or simply the first one
    if worksheet_name and worksheet_name in wb:
        sheet = wb[worksheet_name]
    else:
        sheet = wb[wb.sheetnames[0]]

    this_is_the_first_row = True
    for row in sheet.rows:
        if this_is_the_first_row:  # Read and validate the headers
            this_is_the_first_row = False
            headers = [cell.value for cell in row]
            raise_if_missing_required_headers(headers, required_headers)
            vars = get_corresponding_variable_names(headers, required_headers)
            index_of_var = {var: i for i, var in enumerate(vars)}

            class SpreadsheetRow(object):
                '''View on a spreadsheet row so you can access data as if
                    they were instance variables.
                    '''
                __slots__ = ('__cells',)

                def __init__(self, cells):
                    self.__cells = cells

                def __getattr__(self, attr):
                    content = self.__cells[index_of_var[attr]].value
                    return content

        else:
            yield SpreadsheetRow(row)
开发者ID:leofigs,项目名称:bag,代码行数:58,代码来源:excel.py


示例16: test_leading_opening_brace

    def test_leading_opening_brace(self):
        if sys.version_info[:2] == (2, 6):
            raise SkipTest('Python 2.6 compiler raises a different kind of error')

        try:
            XMLTemplate('<x>${{"a", "b"}</x>')
            assert False, 'must raise'
        except XMLTemplateCompileError as e:
            assert 'Braced expression not terminated' in str(e), e
开发者ID:nandoflorestan,项目名称:kajiki,代码行数:9,代码来源:test_xml.py


示例17: _collect

 def _collect(self, it):
     result = []
     for part in it:
         if part is None:
             continue
         result.append(str(part))
     if result:
         return ''.join(result)
     else:
         return None
开发者ID:drocco007,项目名称:kajiki,代码行数:10,代码来源:template.py


示例18: test_extract_python_inside_invalid

 def test_extract_python_inside_invalid(self):
     src = '''<xml><div>${_('hi' +)}</div></xml>'''
     try:
         x = list(i18n.extract(BytesIO(src.encode('utf-8')), [], None, {
             'extract_python': True
         }))
     except XMLTemplateCompileError as e:
         assert "_('hi' +)" in str(e)
     else:
         assert False, 'Should have raised'
开发者ID:nandoflorestan,项目名称:kajiki,代码行数:10,代码来源:test_xml.py


示例19: content_of

def content_of(paths, encoding='utf-8', sep='\n'):
    if isinstance(paths, Path):
        paths = [str(paths)]
    elif isinstance(paths, basestring):
        paths = [paths]
    content = []
    for path in paths:
        with codecs.open(path, encoding=encoding) as stream:
            content.append(stream.read())
    return sep.join(content)
开发者ID:leofigs,项目名称:bag,代码行数:10,代码来源:text.py


示例20: rewind

 def rewind(self):
     say = self.log.critical
     say('\n' + screen_header('ROLLBACK', decor='*'))
     # Some steps offer a warning because they cannot be rolled back.
     say('\n'.join(self.non_rewindable))              # Display them.
     if not self.rewindable:
         say('No steps to roll back, but the release process FAILED.')
         return
     steps = list(reversed(self.rewindable))
     print('I am about to roll back the following steps:\n{0}'.format(
         ', '.join([str(step) for step in steps])))
     if not bool_input('Continue?', default=True):
         return
     for step in steps:
         self.log.critical(screen_header('ROLLBACK {0}'.format(step)))
         try:
             step.rollback()
         except Exception as e:
             self.log.error('Could not roll back step {0}:\n{1}'
                 .format(step, str(e)))
开发者ID:embray,项目名称:releaser,代码行数:20,代码来源:__init__.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python lexer.lex函数代码示例发布时间:2022-05-27
下一篇:
Python nimfa.mf_run函数代码示例发布时间: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