0

I have a program that prints strings consisting of a random sequence of lowercase letters and spaces.

Is there a way emphasize a certain target word within that string when I print the string to make the target easier to spot in the output?

For example:

Current code:

>>> print(mystring)

mxxzjvgjaspammttunthcrurny dvszqwkurxcxyfepftwyrxqh

Desired behaviour:

>>> some_function_that_prints_with_emphasis(mystring,'spam')

mxxzjvgjaspammttunthcrurny dvszqwkurxcxyfepftwyrxqh

Other acceptable forms of emphasis would be:

  • boldening the characters
  • changing colour
  • capitalizing
  • separating with extra characters
  • any other idea that is easily implemented in Python 3

I'm leaving the requirements deliberately vague because as a beginner I'm not aware of all that Python can do so there might be a simpler way to do this that I've overlooked.

Community
  • 1
  • 1
LMF5000
  • 17
  • 1
  • As far as I know, I'm not sure about boldening or coloring python output. And if the characters are randomly generated, you'd need to backtrack on what you'd already printed to achieve that result, no? – OneCricketeer Dec 24 '15 at 17:02
  • @bhargav-rao I'm not sure this question is duplicate, because the author suggests some alternatives to emphasize the text. – Amaury Medeiros Dec 24 '15 at 17:06
  • @AmauryMedeiros Then vtc as "too broad" – Bhargav Rao Dec 24 '15 at 17:07

3 Answers3

1

Basically everything you're looking for would be done with the curses module; it's designed to perform advanced control over the terminal to do stuff like change colors, bold text, etc. You need to use the various has_* commands to determine terminal capabilities and choose your preferred emphasis style, but after that the docs page and the linked tutorial should give you all the info you need.

For simpler usage, you can just print out the raw terminal escape codes to add and remove color (you just have to split the line up yourself or use re to perform replacements to add the codes). For example, to highlight 'spam' in a line as blue:

myline = "abc123spamscsdfwerf"
print(myline.replace('spam', '\033[94mspam\033[0m'))

For ease of use, you can use ansicolors to avoid having to manually deal with color escapes and the like.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

You can replace the target with its version capitalized:

def emphasis(string, target):
  return string.replace(target, target.upper())
Amaury Medeiros
  • 2,093
  • 4
  • 26
  • 42
0

you could just find the substring you're looking for and put a marker under them, like:

needle = "spam"
haystack = "mxxzjvgjaspammttunthcrurny dvszqwkurxcxyfepftwyrxqh"
pos = haystack.find(needle)
print(haystack)
print(" "*(pos-1) + "^" * len(needle))
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94