将列表转换为不带"join"的字符串 [英] Convert a list to a string without 'join'
问题描述
我正在尝试创建自己的函数,该函数将字符列表转换为字符串.我不允许使用加入".我需要使用循环来执行此操作.我认为我有正确的基础,但是我不确定如何正确地将其实现到功能中.我是编程新手.
I'm trying to create my own function that converts a list of characters into a string. I'm not allowed to use 'join'. I need to use a loop to do this. I think I have the basis of it right, but I'm not really sure how to implement it into the function properly. I'm new to programming.
这是我正在使用的代码:
Here's the code I'm using:
def to_string(my_list):
# This line will eventually be removed - used for development purposes only.
print("In function to_string()")
# Display letters in a single line
for i in range(len(my_list)):
print(my_list[i], end='')
# Separate current letter from the next letter
if i<(len(my_list))-1:
print(", ", end='')
# Returns the result
return ('List is:', my_list)
返回我想要的结果(如果列表为['a','b','c'],则返回a,b,c).但是我们有一个测试文件"用来运行包含以下代码的函数:
That returns the result I want (if the list is ['a', 'b', 'c'] it returns a, b, c). But there's a 'test file' we're meant to use to run the function which contains this code:
print("\nto_string Test")
string = list_function.to_string(str_list1)
print(string)
print(list_function.to_string(empty))
它给出了这个结果:
to_string Test
In function to_string()
r, i, n, g, i, n, g('List is:', ['r', 'i', 'n', 'g', 'i', 'n', 'g'])
In function to_string()
('List is:', [])
这似乎表明我完全搞砸了,这与我认为的打印"功能有关.谁能告诉我我要去哪里错了?
Which seems to indicate that I messed up entirely, something to do with the 'print' function I think. Can anyone please tell me where I'm going wrong?
推荐答案
您的函数打印您的字符串到 stdout
,然后返回列表本身不变.
Your function prints your string to stdout
, then returns the list itself unchanged.
构建一个字符串并返回它而不是打印:
Build a string and return that instead of printing:
def to_string(my_list):
result = ''
last = len(my_list) - 1
for pos, elem in enumerate(my_list):
result += str(elem)
if pos != last:
result += ', '
return result
这会遍历所有元素,并与 枚举保持位置相对()
函数;这样,很容易检测是否将最后一个元素添加到结果中.
This loops over all elements, keeping a position counter with the enumerate()
function; this way it's easy to detect if we are adding the last element to the result.
这篇关于将列表转换为不带"join"的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!