python 我想在“a”后面的数字后面添加“hi”,当出现任何其他字符时,我想按原样返回它[已关闭]

4urapxun  于 2022-12-25  发布在  Python
关注(0)|答案(2)|浏览(130)

这个问题似乎与help center中定义的范围内的编程无关。
3小时前关门了。
Improve this question
所以,我是Python的新手。我尝试了OpenAI的一个名为ChatGPT的A. I代码生成器。它显示了我想要的输出。但是当我在Python编译器中运行相同的代码时,结果却不一样。下面提供了ChatGPT的代码。

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

我期望的输出如下

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"
xqnpmsa8

xqnpmsa81#

不要使用循环,而要使用正则表达式。我建议阅读关于正则的内容,以便更好地理解。
现在,使用以下代码:

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"

参数count=1会将替换次数限制为1。您可以根据需要更改它。
如果有帮助就告诉我。

ogq8wdun

ogq8wdun2#

修改发布以获得预期结果

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
    • 测试**
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

"

相关问题