Python挑战级别3-使用字符串切片解决问题
很抱歉发布了这个问题,其他问题也回答了这个问题。但是,无法找出此解决方案的问题所在。该问题要求找到每侧由3个大写字符包围的小写字符。我写的代码是:Python挑战级别3-使用字符串切片解决问题,python,python-3.x,Python,Python 3.x,很抱歉发布了这个问题,其他问题也回答了这个问题。但是,无法找出此解决方案的问题所在。该问题要求找到每侧由3个大写字符包围的小写字符。我写的代码是: q = '' for i in range(4,len(x)-4): if x[i].islower() and x[i-4].islower() and x[i+4].islower() and x[i-3:i].isupper() and x[i+1:i+4].isupper() : q+=x[i] print(q)
q = ''
for i in range(4,len(x)-4):
if x[i].islower() and x[i-4].islower() and x[i+4].islower() and x[i-3:i].isupper() and x[i+1:i+4].isupper() :
q+=x[i]
print(q)
我得到的线是
“lgvcaaginbkvsoezhtlnldslyitlooqfgiksudtm”
vs‘linkedlist’
谢谢你的帮助
编辑:出于某种原因,以下代码似乎有效:
q = ''
for i in range(4,len(x)-4):
if x[i].islower() and x[i-4].islower() and x[i-3:i].isupper() and x[i+1:i+4].isupper() and x[i+4].islower():
q+=x[i]
print(q)
这将是一个切片解决方案:
t = "This is some TEXtTHAt will result in one true result"
def notupper(x):
return not x.isupper()
yep = []
# lookup function to execute inside all()
terms = {0:notupper, 8:notupper, 4:notupper}
for part in (t[i:i+9] for i in range(len(t)-7)):
if len(part)<9: # fix for XXXxXXX at end of string
part = (part+" ")[:9]
if all(terms.get(index,str.isupper)(ch) for index,ch in enumerate(part)):
print("Statisfies all terms: ", part)
通过从术语
-字典中提取此函数。使用str.isupper
术语的默认参数对part
中没有匹配键的所有索引进行测试。get(index,str.isupper)
all()
isupper和islower()的空格计算为False
阅读:
- 及
您可以通过以下方式替换dict/all
部分:
# the ( .. ) are needed to enable line breaking - you could use \ as well
if notupper(part[0]) and notupper(part[8]) and notupper(part[4]) and (
part[1].isupper() and part[2].isupper() and part[3].isupper() and
part[5].isupper() and part[6].isupper() and part[7].isupper()):
print("Statisfies all terms: ", part)
如果这对于您当前的python级别来说太复杂了。您要做的是匹配一个模式:Not Upper、Upper、Upper、Not Upper、Upper、Upper、Upper、Upper、Not Upper。如果对字符串使用签名,则更容易捕获:
>>> t = "This is some TEXtTHAt will result in one true result"
>>> sig = "".join("U" if c.isupper() else "l" for c in t)
>>> sig
'UllllllllllllUUUlUUUllllllllllllllllllllllllllllllll'
您正在sig
字符串中查找luuul
子字符串。Python没有内置的findall
,但是您可以在find
的结果上进行迭代:
>>> result = ""
>>> i = sig.find("lUUUlUUUl")
>>> while i != -1: # find != -1 means that the substring wasn't found
... result += t[i+4] # the center `l`
... i = sig.find("lUUUlUUUl", i+4) # we can start the next search at the center `l`
...
>>> print( result )
t
您也可以将re.finditer
与正则表达式模式一起使用,但更为复杂。文本在每行末尾都有新行字符“\n”。您需要用空字符串替换所有“\n”字符。这可以使用RegEx(正则表达式)模块完成。添加以下代码行,它将起作用:
import re
x = re.sub(r"\n","", x)
您的测试字符串中没有大写字母。。。有点糟糕的测试用例-不是吗?最后有大写的,这就是你的意思吗?还删除了“True”您只有小写字符:“lgvcaaginbkvsoezhtlnldslyitlooqfgiksudtm”vs“linkedlist”
-其中没有一个“大写字符”
…正则表达式可能更合适?@Austin:“这将符合条件”
-虽然拼写不正确,但我正试着把我的脑袋绕到解决方案,它对给定的字符串不起作用。若要仅返回小写字母,请使用part[4]
@pyt,此选项有效。。如果将print(“Statisfies all terms:,part”)
替换为print(“Statisfies all terms:,part[4])
,并用作t
:t=“””。替换(“\n”,”)
则会得到linkedlist
。。。
import re
x = re.sub(r"\n","", x)