Python:通过ReGex lib [duplicate]同时将小写替换为大写,反之亦然

s6fujrry  于 2023-04-22  发布在  Python
关注(0)|答案(3)|浏览(109)

此问题已在此处有答案

How can I invert (swap) the case of each letter in a string?(9个回答)
昨天关门了。
我打开了这个问题,尽管它在C# lang.中存在重复(没有需要的相关解决方案)。
我尝试用大写字符替换给定字符串中的所有小写字符,反之亦然。这应该以最小的时间复杂度同时完成(因为在大量的口头翻译中使用)。

IO:

  • input:* str_1 =“Www.GooGle.com“
  • output:*“wWW.gOOgLE.COM”
    验证码:
import re                   # import RegEx lib

str_1 = "Www.GooGle.com"    # variable tested

def swapLowerUpper(source):
    # takes source string
    # returns group 0 regex to lower and group 1 regex to upper, by source
    return re.sub(r'([A-Z]+)|([a-z]+)', lambda x: x.group(0).lower(), source)

# check the output
print(swapLowerUpper(str_1)

问题:

我很难触发第二个组(其索引为1)并对其应用属性“.upper()”。我的尝试是将其打开为{x:x.group(0).lower(),x:x.group(1).upper()}失败。

5w9g7ksd

5w9g7ksd1#

如果你的目标是以最少的时间复杂度完成任务,也许利用Python内置方法比依赖正则表达式更有效:

str_1 = "Www.GooGle.com"
print(str_1.swapcase())

使用随机生成的长度为1000个字符的mixalpha字符串进行5000次迭代的效率比较:

import timeit
import re
import random
import string

def swapLowerUpper_regex(source):
    return re.sub(r'([A-Z]+)|([a-z]+)', lambda x: x.group(1).lower() if x.group(1) else x.group(2).upper(), source)

def swapLowerUpper_swapcase(source):
    return source.swapcase()

# Generate a random mixalpha string with length 1000
word = ''.join(random.choices(string.ascii_letters, k=1000))

# Define the number of iterations to run
num_iterations = 5000

# Time the execution of the swapLowerUpper() function using regular expressions
elapsed_times_regex = []
for i in range(num_iterations):
    start_time = timeit.default_timer()
    swapLowerUpper_regex(word)
    elapsed_time_regex = timeit.default_timer() - start_time
    elapsed_times_regex.append(elapsed_time_regex)

# Time the execution of the swapcase() method
elapsed_times_swapcase = []
for i in range(num_iterations):
    start_time = timeit.default_timer()
    swapLowerUpper_swapcase(word)
    elapsed_time_swapcase = timeit.default_timer() - start_time
    elapsed_times_swapcase.append(elapsed_time_swapcase)

# Compute the average elapsed time of each method
avg_elapsed_time_regex = sum(elapsed_times_regex) / len(elapsed_times_regex)
avg_elapsed_time_swapcase = sum(elapsed_times_swapcase) / len(elapsed_times_swapcase)

# Print the average elapsed times
print(f"Average elapsed time using swapLowerUpper_regex(): {avg_elapsed_time_regex:.10f} seconds")
print(f"Average elapsed time using swapLowerUpper_swapcase(): {avg_elapsed_time_swapcase:.10f} seconds")

输出:

Average elapsed time using swapLowerUpper_regex(): 0.0002279637 seconds
Average elapsed time using swapLowerUpper_swapcase(): 0.0000108802 seconds
vlju58qv

vlju58qv2#

检查x.group(1)x.group(2)是否匹配,并返回相应的替换项。

def swapLowerUpper(source):
    return re.sub(r'([A-Z]+)|([a-z]+)', lambda x: x.group(1).lower() if x.group(1) else x.group(2).upper(), source)
jecbmhm3

jecbmhm33#

尝试:

import re

str_1 = "Www.GooGle.com"

str_1 = re.sub(
    r"([a-z]+)|([A-Z]+)",
    lambda g: g.group(1).upper() if g.group(1) else g.group(2).lower(),
    str_1,
)
print(str_1)

图纸:

wWW.gOOgLE.COM

相关问题