Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to scan string and and use upper() between two characters?

Tags:

python

string

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.

like image 327
Rarez Avatar asked Oct 20 '15 20:10

Rarez


People also ask

How do I extract a string between two characters in Python?

Using index() + loop to extract string between two substrings. In this, we get the indices of both the substrings using index(), then a loop is used to iterate within the index to find the required string between them.

How do you convert string to upper in Python?

Python String upper() Method The upper() method returns a string where all characters are in upper case.

How do you extract part of a string in Python?

You can extract a substring in the range start <= x < stop with [start:step] . If start is omitted, the range is from the beginning, and if end is omitted, the range is to the end. You can also use negative values. If start > end , no error is raised and an empty character '' is extracted.

How do you find the uppercase of a string in Python?

What is isupper() in Python. In Python, isupper() is a built-in method used for string handling. This method returns True if all characters in the string are uppercase, otherwise, returns “False”.


1 Answers

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.

like image 71
Kerem Avatar answered Nov 10 '22 05:11

Kerem