-1

I began python not a long time ago, and i am doing a program that sometimes needs to make a lot of repetitions in function of different entries. it takes a lot of place, I think it makes the program work slower, and most of all, im limited if I want to in high numbers. here is an example of these type of repetitions:

if len(input) == 1:
    text1, textx = text.split('\n')
elif len(input) == 2:
    text1, text2, textx = text.split('\n')
elif len(input) == 3:
    text1, text2, text3, textx = text.split('\n')
elif len(input) == 4:
    text1, text2, text3, text4, textx = text.split('\n')
elif len(input) == 5:
    text1, text2, text3, text4, text5, textx = text.split('\n')
elif len(input) == 6:
    text1, text2, text3, text4, text5, text6, textx = text.split('\n')
elif len(input) == 7:
    text1, text2, text3, text4, text5, text6, text7, textx = text.split('\n')
elif len(input) == 8:
    text1, text2, text3, text4, text5, text6, text7, text8, textx = text.split('\n')

if someone could give me a solution to avoid that, it would be really nice and helpful. thanks, have a great day :)

hmngwn
  • 9
  • 3

2 Answers2

1

this is bad code in my opinion, I would rarely solve something using this technique. but assuming you insist on using this technique.

You could use dict comprehension. (This might be advanced)

What is "dict comprehension" guide: https://www.datacamp.com/community/tutorials/python-dictionary-comprehension

I dont understand "enumerate" guide: https://www.geeksforgeeks.org/enumerate-in-python/

I have never heard of dictionaries guide: https://www.youtube.com/watch?v=ZEZdys-fHDw

So the idea is that you store al your "text" variables as dictionary keys and al the values for it as dictionary values :)

def stackoverflow(list):
    dictionary = {f"text{num+1}":text for num , text in enumerate(list.split('\n'))}
    if "text1" in dictionary: #check if this value exists
        print(dictionary["text1"]) # get the key from the dictionary and print its value
    return dictionary # return the dictionary you just created


print(stackoverflow("I'm Greg btw\nhow are you\nare you enjoying your coding career?"))
print(stackoverflow("I'm a second year computer scientist\n Keep putting in the work my friend"))
Greg W.F.R
  • 544
  • 1
  • 5
  • 13
0

str.split returns a list, which is much more convenient to deal with than an arbitrary number of variables. That entire block of code can be reduced to:

textx = text.split('\n')
luther
  • 5,195
  • 1
  • 14
  • 24