Reputation: 129
I'm a beginner so please forgive me for that question. I would like write program which magnifies letters between characters "<" and ">"
For example Input:
<html> randomchars </html>
Output:
<HTML> randomchars </HTML>
How to do that ?
I only wrote this but this magnifies all words.
while True:
inp = input()
if inp == "":
break
elif inp =="<":
inp=inp.upper()
print(inp)
else:
print(inp)
Thanks for help.
Upvotes: 6
Views: 3433
Reputation: 2897
Try re.sub;
print re.sub(r"(</?\w+>)", lambda up: up.group(1).upper(), "<tag>input</tag>")
/?\w+
breakdown below, assuming you can see parenthesis ()
makes the group and we are trying to match between brackets <>
;
?
will greedily match 0 or 1 repetitions of the preceding RE.
Therefore, /?
will match both start and finish tags.\w
will match any Unicode word character, including a-z, A-Z, and 0-9.+
will greedily match 1 or more repetitions of the preceding RE.This will match most tags and then you can replace the tag after converting to uppercase inline using the lambda function, up
.
Upvotes: 2
Reputation: 61
You want to use a regular expression to match the tags, and pass a function to modify the match. See this previous answer: Making letters uppercase using re.sub in python?
def upper_repl(match):
return match.group(1).upper()
re.sub('(<[^>]*>)', upper_repl, '<span> <hey <annoy!>> </span>')
'<SPAN> <HEY <ANNOY!>> </SPAN>'
Upvotes: 0
Reputation: 77857
First, let's "repair" the while loop to get the continuation control out of the way. Instead of
while True:
inp = input()
if inp == "":
break
<process the input>
use
inp = input()
while inp != "":
<process the input>
inp = input()
Now, for the loop innards. We need to process "inp" to throw the marked characters into upper case. We also want to do this in a fashion a beginner can understand, matching the original loop flow.
You need to iterate through the characters in the input string. Set a boolean flag to tell you whether or not you're in a marked area.
upper_area = False
out_str = ""
for char in inp:
if char == '>':
upper_area = False
elif char == '<':
upper_area = True
elif upper_area:
char = char.upper()
out_str += char
Upvotes: 0