首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python for循环只执行字符串中的第一个元素,而不遍历字符串的其余部分

Python for循环只执行字符串中的第一个元素,而不遍历字符串的其余部分
EN

Stack Overflow用户
提问于 2019-10-26 08:58:53
回答 1查看 49关注 0票数 0

我正在做一个学校的项目。我希望我的for循环循环遍历字符串并将每个字母转换为盲文,但它只转换字符串的第一个元素。

代码:

代码语言:javascript
复制
def word_to_braille(word):

    '''(str) -> str
    Given a string with no spaces and no newlines, convert to a Braille o-string.
    Put two newlines in between every Braille cell.
    The print_ostrint function we use in the doctest is to make the output more readable.

    Remember digits should have NUMBER before them.
    Capital letters should have CAPITAL before them unless...
        ...all of the variable "word" is capital letters and there are at least two capital letters.**
        In that case: put CAPITAL twice at the front instead.
        Hint: remember the helper function is_all_caps.
    >>> print_ostring(word_to_braille('CHAT'))
    .o .o oo o. o. .o
    .. .. .. oo .. oo
    .o .o .. .. .. o.
    '''
    if is_all_caps(word):
        for i in word:
            return ('.o\n..\n.o\n\n' + '.o\n..\n.o\n\n') + char_to_braille(i)

期望值:

代码语言:javascript
复制
.o .o oo o. o. .o
.. .. .. oo .. oo
.o .o .. .. .. o.

输出:

代码语言:javascript
复制
.o .o oo
.. .. ..
.o .o ..

帮助器函数在其他地方定义,但它们通过测试时没有出现问题。如果问题的格式不合适,很抱歉,这是我在本网站上的第一个问题:)

EN

回答 1

Stack Overflow用户

发布于 2019-10-26 10:12:20

您需要将" return“移出循环,因为它用于结束函数运行并返回值。

相反,您应该将每次迭代的结果附加到一个变量,然后在循环完成后返回该变量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58567232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档