Python:巧妙的字符串操作方法

2 投票
3 回答
1022 浏览
提问于 2025-04-16 10:15

我刚开始学习Python,现在正在读《Dive into Python》这本书里的字符串处理章节。

我想知道,有哪些比较好的(或者说聪明/创意十足的)方法来完成以下几个任务:

1) 从这个字符串 "stackoverflow.com/questions/ask" 中提取出单词 'questions'。我用 string.split(/)[0] 试过了,但感觉这方法不太聪明。

2) 在给定的数字或字符串中找到最长的回文(就是正着读和反着读都一样的字符串)。

3) 从一个给定的单词(比如 "cat")开始,找出所有可能的方法,通过一次改变一个字母,变成另一个三字母的单词(比如 "dog"),并且每次改变后的字母组合都要是一个有效的单词。

比如说:cat, cot, dot, dog。

3 个回答

0

第三种方法:

如果你的字符串是 s

你可以用下面这段代码:

max((j-i,s[i:j]) for i in range(len(s)-1) for j in range(i+2,len(s)+1) if s[i:j]==s[j-1:i-1:-1])[1]

这段代码会给你返回结果。

2

作为个人练习,我给你们带来了(希望)注释清晰的代码和一些提示。

#!/usr/bin/env python2

# Let's take this string:
a = "palindnilddafa"
# I surround with a try/catch block, explanation following
try:
  # In this loop I go from length of a minus 1 to 0.
  # range can take 3 params: start, end, increment
  # This way I start from the thow longest subsring,
  # the one without the first char and without the last
  # and go on this way
  for i in range(len(a)-1, 0, -1):
    # In this loop I want to know how many 
    # Palidnrome of i length I can do, that
    # is len(a) - i, and I take all
    # I start from the end to find the largest first
    for j in range(len(a) - i):
      # this is a little triky.
      # string[start:end] is the slice operator
      # as string are like arrays (but unmutable).
      # So I take from j to j+i, all the offsets 
      # The result of "foo"[1:3] is "oo", to be clear.
      # with string[::-1] you take all elements but in the
      # reverse order
      # The check string1 in string2 checks if string1 is a 
      # substring of string2
      if a[j:j+i][::-1] in a:
        # If it is I cannot break, 'couse I'll go on on the first
        # cycle, so I rise an exception passing as argument the substring
        # found
        raise Exception(a[j:j+i][::-1])

# And then I catch the exception, carrying the message
# Which is the palindrome, and I print some info
except Exception as e:
  # You can pass many things comma-separated to print (this is python2!)
  print e, "is the longest palindrome of", a
  # Or you can use printf formatting style
  print "It's %d long and start from %d" % (len(str(e)), a.index(str(e)))

在讨论之后,如果有点偏题我很抱歉。我写了另一个回文搜索器的实现,如果sberry2A可以的话,我想知道一些基准测试的结果!

请注意,代码中可能有很多关于指针的错误,还有那个让人头疼的“+1 -1”问题,但思路是清晰的。我们从中间开始,然后向外扩展,直到无法再扩展为止。

以下是代码:

#!/usr/bin/env python2


def check(s, i):
  mid = s[i]
  j = 1
  try:
    while s[i-j] == s[i+j]:
      j += 1
  except:
    pass
  return s[i-j+1:i+j]

def do_all(a):
  pals = []
  mlen = 0
  for i in range(len(a)/2):
    #print "check for", i
    left = check(a, len(a)/2 + i)
    mlen = max(mlen, len(left))
    pals.append(left)

    right = check(a, len(a)/2 - i)
    mlen = max(mlen, len(right))
    pals.append(right)

    if mlen > max(2, i*2-1):
      return left if len(left) > len(right) else right

string = "palindnilddafa"

print do_all(string)

撰写回答