I am learning and I am trying to make this code nicer and learn more in pythonic way! I wanna turn this code into a one line code inside list (list comprehension). e.g., [here goes the new implementation]
def main():
inp = input()
x = []
x_tm = ''
for i in range( 0, len(inp)):
if inp[i] == ',':
x.append(x_tm)
x_tm = ""
continue
if inp[i] ==" ":
continue
x_tm = inp[i]
x.append(inp)
CodePudding user response:
There is a built-in function called "split" that does what you wrote.
def main():
inp = input("Enter text: ").split(",")
print(inp)
If you want to write the function yourself it would look something like this:
def main():
inp = input("Enter text: ")
temp = ""
words = []
for ltr in inp:
if ltr == ",":
words.append(temp)
temp = ""
else:
temp = ltr
if len(temp):
words.append(temp)
print(words)
CodePudding user response:
Your function reads a line, then computes something from it without printing, returning, or any other kind of "output". Hence here's an equivalent one liner:
main = input
