0

This is my code:

list = []
text = input("Please give your text:")
text = str(text)
list.append(text)
list = str(list)

And I want to give the input, for example: abcd. Then, I want it to split it in ["a","b","c","d"]

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
BOB
  • 59
  • 2
  • 8

4 Answers4

3

Another option:

text = input("Please give your text:")
l = list(text)
print (l)
Joe
  • 12,057
  • 5
  • 39
  • 55
2

First, avoid naming your variable as list. You can then, split a str into list just by saying list(text).

lst = []
text = input("Please give your text:")
lst.extend(list(text))
print (lst)

Output

['a', 'b', 'c', 'd']
Sunitha
  • 11,777
  • 2
  • 20
  • 23
0

Access the characters by Index. By iterating over the string, you can pull out each character individually. The variable i will be equal to index 0 to the length of text and you can access the character elements by index with text[i]. See example below:

user_input_as_chars = []
text = input("Please give your text:")
for i in range(0, len(text)):
    user_input_as_chars.append(text[i])
user_input_as_chars = str(list)

Another approach is to traverse the Strings as an iterable:

for char in text:
    user_input_as_chars.append(char)
ChickenFeet
  • 2,653
  • 22
  • 26
  • 4
    your solution is overcode. – Brown Bear Jul 23 '18 at 07:30
  • Maybe so, but it is arguably easier to follow for a beginner to Python. _This isn't code golf_. – ChickenFeet Jul 23 '18 at 07:32
  • It's not "let's teach antipatterns to newcomers" either. a) using `list` as a variable name. b) creating an empty list only to extend it later when it could be created entirely by a single call to `list()` (if you hadn't shadowed it). c) calling `str()` on a string. d) iterating through a string by indexing instead of item iteration. – Tim Pietzcker Jul 23 '18 at 07:40
  • 1
    Six lines instead of a single `l = list(input("Please give your text:"))`... – Tim Pietzcker Jul 23 '18 at 07:41
  • 1
    @TimPietzcker that being said, you still have valid points above. Sorry I didn't inspect BOB's code very thoroughly. – ChickenFeet Jul 23 '18 at 08:44
0
text = input("Please give your text:")
list.extend(list(text))
print (list)
Techgeeks1
  • 556
  • 1
  • 4
  • 18