Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python3中的函数返回格式正确的值_Python_Python 3.x_Function_Formatting - Fatal编程技术网

从Python3中的函数返回格式正确的值

从Python3中的函数返回格式正确的值,python,python-3.x,function,formatting,Python,Python 3.x,Function,Formatting,正在编写一个我认为我已经完成的编码程序,并且我得到了正确的值。但是,测试条件正在寻找以不同方式格式化的值。而且我在弄清楚如何在我的函数中正确设置返回的格式时失败了 在查找答案时,我正确获得了值: [4,15,7,19,1,20,13,9,4,14,9,7,8,20] 但测试条件预计 应等于“2085141182381121315151419209141497820” 我这辈子都没能弄明白这一点 在此处查看原始问题: 对Python来说仍然很陌生,但我尽我所能解决这些问题。代码可能很难看,但它是我

正在编写一个我认为我已经完成的编码程序,并且我得到了正确的值。但是,测试条件正在寻找以不同方式格式化的值。而且我在弄清楚如何在我的函数中正确设置返回的格式时失败了

在查找答案时,我正确获得了值:

[4,15,7,19,1,20,13,9,4,14,9,7,8,20]

但测试条件预计

应等于“2085141182381121315151419209141497820”

我这辈子都没能弄明白这一点

在此处查看原始问题:

对Python来说仍然很陌生,但我尽我所能解决这些问题。代码可能很难看,但它是我的

编辑:我正在寻找一种将返回语句重新格式化为字符串而不是整数列表的方法

提前谢谢你的帮助!感谢您的帮助,即使是如何在这里发布更好的问题

Koruptedkernel

import string

def alphabet_position(positions):
    #Declaring final position list.
    position = []
    #Stripping punctuation from the passed string.
    out1 = positions.translate(str.maketrans("","", string.punctuation))
    #Stripping digits from the passed string.
    out = out1.translate(str.maketrans("","", string.digits))
    #Removing Spaces from the passed string.
    outter = out.replace(" ","")
    #reducing to lowercase.
    mod_text = str.lower(outter)
    #For loop to iterate through alphabet and report index location to position list.
    for letter in mod_text:
        #Declare list of letters (lower) in the alphabet (US).
        alphabet = list('abcdefghijklmnopqrstuvwxyz')
        position.append(alphabet.index(letter) + 1)
    return(position)

#Call the function with text.
alphabet_position("The sunset sets at twelve o'clock.")



以下是你的家庭作业和一些解释(使用最好的理解):

#完整的字母表(从技术上讲是一个列表)
字母表='abcdefghijklmnopqrstuvxyz'
#每个字母和索引+1
字母表_dict={u:str(i+1)表示枚举(字母表)中的i,u}
def字母表位置(文本):
#将文本字符映射到相应的aplhabet_dict项
pos_list=[alphabet_dict.get(char.lower())
如果字母表中的char.lower()为文本中的char\u dict]
#转换为他们要求的疯狂字符串格式
返回“”。加入(位置列表)
字母表位置(“日落时间定在十二点。”)
输出:

“20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 3 11”

在字典方面做了一些很好的功课,并且尝试并成功地做到了这一点

回到了我原来的方式(没有那么干净或高效),但通过将for循环更改为,成功地转换了列表

position.append(str(alphabet.index(letter) + 1))

然后用


return ' '.join(position)

以他们测试的格式得到答案

对!!我解决了一件事

感谢所有的帮助,我将努力更好地制定问题,以获得更好的帮助


TYTY

您只是在问如何将列表转换为字符串吗?因为您的程序确实为给定的输入提供了正确的列表。您在本文中的主要想法/问题是不可理解的,而且您的代码有缩进错误。请重新编辑您的postEdited注释以修复代码中的缩进。是否最好将位置变量更改为字符串,然后返回它?我尝试了几次,但失败了(仅在之后返回[])