I don't want to use a for statement, but I want to combine characters in the list into a single string

Asked 2 years ago, Updated 2 years ago, 42 views

I don't want to use a for statement, but I want to combine characters in the list into a single string

a = ['a','b','c','d']

Same list type

a = 'abcd'

I'm going to change it to one string My code was made using a for statement, but how can I make it shorter without using a for statement?

a = ['a','b','c','d']

result = ""
for i in a:
    result += i

string python

2022-09-22 12:16

1 Answers

Use the str.join(iterable) method in an empty string.

The str.join(iterable) method attaches itable after the str.

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(''.join(a))
print(''.join(a[:4]))

Output:

abcdefg
abcd


2022-09-22 12:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.