+ 1

How to print a certain index differently.

If you know Python's Colorama module, you know you can print out a string in whatever color you like right. Example: import colorama print(colorama.Fore.RED + "This is gonna be printed out in red") print(colorama.Fore.GREEN + "This is gonna be printed out in green") Now back to my question, how do i loop through a list but do something (change the color) when the index is equal to i. i mean something like: for i in mylist: print(i) but if i == mylist[2], print it but in a different color. Eg. Mylist = ["David", "holmes, "ngandu"] Expected output: David <default printing color> Holmes <color red> Ngandu <default printing color>

15th Mar 2022, 11:29 AM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
4 Respuestas
+ 3
Your question has the answer itself. Mylist = ["David", "holmes, "ngandu"] for name in Mylist: if name == Mylist[1]: print(Fore.RED+name) else: print(name)
15th Mar 2022, 11:38 AM
Simba
Simba - avatar
+ 3
Works fine here. Try again myletters = ['a', 'b', 'c', 'b', 'd'] for letter in myletters: if letter == myletters[1]: green letter else: white letter
15th Mar 2022, 12:26 PM
Simba
Simba - avatar
0
Simba nope didn't work the way i want it to. Example 2. myletters = ['a', 'b', 'c', 'b', 'd'] Now let's say i want to print out everything in the same order they are, but all 'b's in a different color (eg green): Expected output: ['a' <in color white>, 'b' <in color GREEN>, 'c' <in color white>, 'b' <in color GREEN>, 'd' <in color white] Printing it yo way produces: ['a' <in color white>, 'b' <in color GREEN>, 'c' <in color GREEN>, 'b' <in color GREEN>, 'd' <in color GREEN]
15th Mar 2022, 12:02 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
0
Simba screenshot the whole code in console
15th Mar 2022, 12:28 PM
David Holmes Ng'andu
David Holmes Ng'andu - avatar