Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace with upper(string)
#1
I need to find all strings like this: \nd string \nd*
where string is any alphabetic string, eg. [A-z]+

I then need to replace it by upper(string)

For instance: "Here is a \nd Word \nd* in upper case", must become "Here is a WORD in upper case"

Can this be achieved using regex? If not, how can I achieve it?
Reply
#2
If the sequence is always the same, then this may do what you need:

def to_upper(text):
    output = ""
    list_text = text.split("\nd")
    for index, words in enumerate(list_text):
        word = words.lstrip("*")
        if index == 1:
            output += word.upper()
        else:
            output += word.strip()
    return output


txt = "Here is a \nd Word \nd* in upper case"
print(to_upper(txt))
txt = "This is another \nd example \nd*"
print(to_upper(txt))
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
re.sub() can do that.
import re

test_str = r"Here is a \nd Word \nd* in upper case"
pattern = r"(\\nd(.*)\\nd\*)"  # Backslash pattern fun!


def repl_func(match):
    return match.group(2).upper()


print(re.sub(pattern, repl_func, test_str))
Output:
Here is a WORD in upper case
The extra spaces are contained in the test_str. Not sure if you want them stripped off or not.
Reply
#4
Thank you deanhystad,
There is just one small shortcoming (I admit I did not mention it!) in that if the \nd...\nd* string appears more than once, it messes it up:

import re
 
test_str = r"Here is a \nd Word\nd* in upper case and \nd another\nd* "
pattern = r"(\\nd(.*)\\nd\*)"  # Backslash pattern fun!
 
 
def repl_func(match):
    return match.group(2).upper()
 
 
print(re.sub(pattern, repl_func, test_str))
Output: Here is a WORD\ND* IN UPPER CASE AND \ND ANOTHER

Should be: Here is a WORD in upper case and ANOTHER
Reply
#5
Need to modify the pattern to not be greedy.

https://docs.python.org/3/howto/regex.ht...non-greedy
Reply
#6
This is probably a home assignment. Therefore I assume that understanding of underlying algorithm is expected.

This is basically: "parse every word, mark start of uppercasing words, uppercase words until stop mark is reached". So basic if...elif..else can be used:

text = r"Here is a \nd Word what is\nd* in upper case and \nd another\nd* "

def convert(text, start=False):
    for word in text.split():
        if word == r'\nd':
            start = True
        elif word.endswith(r'\nd*'):
            yield word.removesuffix(r'\nd*').upper()
            start = False
        else:
            if start:
                yield word.upper()
            else:
                yield word

print(' '.join(convert(text)))

-> Here is a WORD WHAT IS in upper case and ANOTHER
I am well aware that this code has gotchas :-) but in learning process it useful to find them yourself.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
I played around myself and found that this works:

text = r"Here is a \nd Word\nd* that is in upper case and \nd another\nd* one of them"
 
def MakeUpper(text):
    ttxt=""
    while True:
        nd=text.find("\\nd")
        if nd == -1:
           break
        ndstar=text.find("\\nd*")
        text=text[0:nd]+text[nd+3:ndstar].upper().strip()+text[ndstar+4:]
    return text            

upr=MakeUpper(text) 
print(upr)
Output: Here is a WORD that is in upper case and ANOTHER one of them
Reply
#8
(Feb-10-2023, 06:37 AM)deanhystad Wrote: Need to modify the pattern to not be greedy.

https://docs.python.org/3/howto/regex.ht...non-greedy

Thank you for this. It works like a charm
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 776 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,217 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Find and Replace numbers in String giddyhead 2 1,245 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  AttributeError: 'list' object has no attribute 'upper' Anldra12 4 4,913 Apr-27-2022, 09:27 AM
Last Post: Anldra12
  Replace String in multiple text-files [SOLVED] AlphaInc 5 8,168 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
  Replace String with increasing numer [SOLVED] AlphaInc 13 5,074 Aug-07-2021, 08:16 AM
Last Post: perfringo
  How to replace on char with another in a string? korenron 3 2,370 Dec-03-2020, 07:37 AM
Last Post: korenron
  How can I add string.upper() noahneature 2 1,874 Oct-11-2020, 06:41 PM
Last Post: noahneature
  Replace string in many files in a folder metro17 8 5,623 Oct-16-2019, 06:46 PM
Last Post: ndc85430
  open, read and replace a string in a file Reims 0 1,818 Oct-02-2019, 01:30 PM
Last Post: Reims

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020