[*string] vs list(string) | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

[*string] vs list(string)

Okay, imagine i have a string, say 'abc def'. If i want to split it into individual characters, i could do [*string] or i could do list(string) which output the same thing ['a', 'b', 'c', ' ', 'd', 'e', 'f']. I was wondering, without using split, a) are there other methods that could work b) what is the difference between list(string) and [*string]? Can they be used interchangably and which one is more readable?

12th Dec 2023, 1:37 PM
5Just
5Just - avatar
4 Antworten
+ 3
Edited with errors rectified as pointed out by Rain. You can use a for loop to split it up if you want more control. You can then choose to omit the space (or any other character). string = "abc def" list = [ ] for char in string: if char == " ": continue list.append(char) print(list) This also works the other way. list = ['a', 'b', 'c', ' ', 'd', 'e', 'f'] string = "" for char in list: if char == " ": continue string += char print(string)
12th Dec 2023, 7:55 PM
StuartH
StuartH - avatar
+ 3
StuartH , list ['a', 'b', 'c', ' ', 'd', 'e', 'f'] should be list = ['a', 'b', 'c', ' ', 'd', 'e', 'f'] and for char in string: (the second time) should be for char in list: It's inconvenient that you can't flip over to the Code Playground when writing a comment to test for typos. I used to use the playgrounds of various websites, such as w3schools.com, for that. Now I have Pydroid 3 on my Android phone. There's a risk using list as a variable name, because that's already the name of the constructor for the list class. If you later try to use that constructor, befuddled = list("flabbergasted") you'll get, TypeError: 'list' object is not callable Since list isn't a keyword, you won't get a SyntaxError when assigning to it. Python will happily overwrite the identifier with a new reference. I suspect some IDEs warn you about names like that, but Pydroid 3 doesn't, so I'm learning what to avoid little by little.
13th Dec 2023, 12:24 AM
Rain
Rain - avatar
+ 2
# I like this trick: print(*"spaced") # s p a c e d
12th Dec 2023, 11:03 PM
Rain
Rain - avatar
0
Stuart, yes, i could, but it wont be that compact. Alas, i want it to be readable
13th Dec 2023, 5:59 AM
5Just
5Just - avatar