Home > Mobile >  I want to add "hi" after numbers after "a". and when any other characters occur
I want to add "hi" after numbers after "a". and when any other characters occur

Time:12-25

So, I am new to python. I tried an A. I code generator called ChatGPT by OpenAI. It shows the output of what I want. But when I run the same code in python compilers, the results are not the same. The code by ChatGPT is provided below.

def add_degree_symbol(string):
    result = ""
    numbers_after_a = False
    for c in string:
        if c == "a":
            numbers_after_a = True
            result  = c
        elif c in "bcdefghijklmnopqrstuvwxyz":
            numbers_after_a = False
            result  = c
        elif numbers_after_a and c in "0123456789":
            result  = c   "hi"
        else:
            result  = c
    return result

I am Expecting Outputs like

print(add_degree_symbol("a123b"))  # outputs "a123hib"
print(add_degree_symbol("a123 456b"))  # outputs "a123hi 456b"
print(add_degree_symbol("a123*456b"))  # outputs "a123hi*456b"
print(add_degree_symbol("abcdefghijklmnopqrstuvwxyz"))  # outputs "abcdefghijklmnopqrstuvwxyz"
print(add_degree_symbol("a1234567890b"))  # outputs "a1234567890hib"

CodePudding user response:

Instead of using loops, use a regular expression. I would suggest reading about regular for better understanding.

For now, use this code:

import re

def add_deg(string):
    # Create a regular expression to match "a" followed by a number
    pattern = r"a\d"
    # Use re.sub() to replace the first occurrence of the pattern with ")deg" added after the number
    return re.sub(pattern, r"\g<0>)deg", string, count=1)

# Test the function
print(add_deg("abc123def456"))  # Output: "abc123)degdef456"
print(add_deg("abcdef"))  # Output: "abcdef"

The argument count=1 will limit the number of substitutions to 1. You can change it as per your need.

Let me know if this helps.

CodePudding user response:

Modification of posted to obtain expected results

def add_degree_symbol(string):
    result = ""
    numbers_after_a = False
    for c in string:
        if c == "a":
            numbers_after_a = True
            result  = c
        elif numbers_after_a and not c in "0123456789":
            result  = "hi"   c
            numbers_after_a = False
        else:
            result  = c
    return result

Tests

print(add_degree_symbol("a123b"))  # outputs "a123hib" 
print(add_degree_symbol("a123 456b"))  # outputs "a123hi 456b" 
print(add_degree_symbol("a123*456b"))  # outputs "a123hi*456b" 
print(add_degree_symbol("abcdefghijklmnopqrstuvwxyz"))  # outputs "abcdefghijklmnopqrstuvwxyz" 
print(add_degree_symbol("a1234567890b"))  # outputs "a1234567890hib

"

  • Related