Ask Your Question

How can I change the Color of the Output of a Substring of a String in Python when printing to the Command Line?

asked 2023-04-05 14:21:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2023-04-05 14:24:04 +0000

qstack gravatar image

You can use ANSI escape codes to change the color of the output of a substring of a string in Python when printing to the command line.

Here's an example:

string = "Hello, world!"
substring = "world"

# Print the string with the substring in green
print(string.replace(substring, "\033[32m{}\033[0m".format(substring)))

In this example, the substring "world" is replaced with the ANSI escape code \033[32m (which changes the color to green), followed by the substring itself, and then the reset code \033[0m (which resets the color back to the default).

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools

1 follower


Asked: 2023-04-05 14:21:00 +0000

Seen: 28 times

Last updated: Apr 05 '23