Python Forum

Full Version: I want to simplify this python code into fewer lines, it's about string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I want to simplify this python code into fewer lines as possible, but I'm less experienced and I cannot do it:

code = [0, 1, 0, 1, 0, 1, 0, 1] # This is a separated line, which will be used as an argument in a function

def f(code, i):
    return ["a", "b", "c", "d", "e"][code[i]]
for i in range(len(code)):
    c += f(code, i)
print(c)
Output:
abababab
An example of simplification:
code = [0, 1, 0, 1, 0, 1, 0, 1] # This is a separated line, which will be used as an argument in a function

def f(code, i): # This is ok, in my real project, it's already simplified, this is just a draft.
    return ["a", "b", "c", "d", "e"][code[i]]
c = [x for x in ["a", "b", "a", "b", "a", "b", "a", "b"]] # this is wrong, it should using the function f, but I don't know how to do it?
print(c) # This shows list of characters, but not one string, so it's wrong.
Output:
['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
Just needs switching around a little and make use of str join method, the function is not needed.
c = "".join(["a", "b", "c", "d", "e"][index] for index in code)
maybe

code = [0, 1, 0, 1, 0, 1, 0, 1]
letters = ["a", "b", "c", "d", "e"]

def f():
    c = ''
    for i in range(len(code)):
        c += letters[code[i]]
    return c
    
print(f())
My question for clearer, is how to turn a list of characters into one single string?
c = ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
c = ... # What should be this line?
print(c)
It should print:
abababab

Edit: Solved
using join as one of you explained, bye.
Use the str method join as stated in my post above.
c = ['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
c = "".join(c)
print(c)
Output:
abababab
Thank you so much.