我试图制作一个单行函数来交换字符串大小写,但它不起作用。一切都是有道理的,但是该函数返回的是传入它的相同字符串,没有任何更改。
import re
def swap_case(string):
return re.sub('([A-Z])([a-z]+)', r'\1'.lower()+'\2'.upper(), string)
您的正则表达式模式可能与输入字符串的结构不匹配,例如,如果第一个字符是小写,然后是第二个大写。这是一个使用re.sub回调函数的版本:
def swap_case(string):
return re.sub(r'.', lambda x: x.group().upper() if x.group() == x.group().lower() else x.group().lower(), string)
inp = "Hello World"
print(swap_case(inp)) # hELLO wORLD
上述解决方案通过将每个字符从小写转换为大写,反之亦然。
认为这是正确的想法,但它不想将字符串转换为.lower()或.upper()直到从正则表达式操作返回这些值。不知道你会如何做一个单线。他们有几种不同的迭代方法。 .findall()没问题,'因为你可以打印每个字母,看看它在做什么很容易。
#! /usr/bin/env python3
import re
def swap_case( string ):
newstring = ''
for s in re .findall( r'([\w ]{1})', string ):
## print( s )
try: newstring += re .match( r'([A-Z ])', s ) .group(1) .lower()
except: newstring += re .match( r'([a-z])', s ) .group(1) .upper()
return newstring
print( swap_case( 'THIS is A string' ) )
这是一个字符串
如其他答案所述,您的 rexexp 可能与输入字符串不匹配。作为一种替代解决方案,这是一个简单的单行代码,它通过迭代字符串的字符来工作:
def swapcase(s):
return ''.join(ch.upper() if ch.islower() else ch.lower() for ch in s)
当然,您也可以简单地使用str.swapcase(); 请参阅https://docs.python.org/3/library/stdtypes.html#str.swapcase。