-1

I have a string that is converted to a list using the split() function, and I want to split my single item into multiple items each containing one character.

Here's my code:

string = "ABCDEFG"
x = string.split()
print(x)

Thank you for your time!:D

  • Welcome to Stack Overflow! Your question will be clearer, and will attract better answers, if you include: 1. the output do you get when you run the code you have, and 2. the correct output you want. – Jim DeLaHunt Feb 17 '20 at 17:22
  • Does this answer your question? [How to split a string into array of characters?](https://stackoverflow.com/questions/4978787/how-to-split-a-string-into-array-of-characters) – Kenny Ostrom Feb 17 '20 at 17:23

2 Answers2

1

str.split(separator, maxsplit) method returns a list of strings after breaking the given string by the specified separator.

separator: The is a delimiter. The string splits at this specified separator. It is not provided then any white space is a separator.

maxsplit: It is a number, which tells us to split the string into a maximum of the provided number of times. If it is not provided then there is no limit.

You can do this if you want to split it into a list of single characters.

x='ABCDEFG'
char_list=list(x)
#['A', 'B', 'C', 'D', 'E', 'F', 'G']

If you want to split it into single characters avoiding any spaces then try this.

x='abcde fgh   i'
out=[char for string in x.split() for char in string]
#['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

And .split() doesn't convert your string to a list. In your, it returned ['ABCDEFG] because the string contains no spaces.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
0

Use the for loop :

# Driver code 
string = "ABCDEFG"
print(split([char for char in string])) 

Or the list:

string = "ABCDEFG"
print(list(string))
ChickenMinh
  • 39
  • 1
  • 2
  • 11