1. 程式人生 > >python字串相關練習

python字串相關練習

練習一:

輸入一個字串 s, 返回 
由字串的最前面兩個字母和最後兩個字母組成的字串。
例如: 'spring' 返回 'spng', 'is' 返回 'is'
當輸入的字串長度小於2時,返回空字串

def both_ends(s):
    if len(s)<2:
        print ''
    elif len(s)==2:
        print(s)
    else:
        print(s[0]+s[-1])
    return
both_ends('afasdfa')

輸出結果:

練習二:

輸入一個字串s, 返回滿足以下條件的字串
1.找出與字串的第一個字母相同的字母,把它們替換成 '*',除了第一個字母本身以外
例如: 輸入'babble', 返回 'ba**le'
提示:使用 s.replace(stra, strb) 函式,可以將字串 s 中的所有 子字串stra 替換為 子字串strb

def fix_start(s):
    f1=s[0]
    b1=s[1:]
    fix_back = b1.replace(f1,'*')
    return f1+fix_back
print fix_start('babble')

輸出結果:

練習三:

輸入字串 a 和 b, 返回新增以下條件的字串
1.使用空格把兩個字串分隔後合併成一個字串
2.交換兩個字串的最前面的兩個字母
3.字串 a 和 b 的長度都大等於2
例如: 'mix, pod' -> 'pox mid'
  'dog', 'dinner' -> 'dig donner'

def mix_up(a, b):
    m1 = a[0]+b[1]+a[2:]
    m2 = b[0]+a[1]+b[2:]
    return m1+m2

print mix_up('mix','pod')
print mix_up('dog','dinner')

輸出結果;

練習四:

Given a string, find the first appearance of the
substring 'not' and 'bad'. If the 'bad' follows
the 'not', replace the whole 'not'...'bad' substring
with 'good'.
Return the resulting string.
So 'This dinner is not that bad!' yields:
This dinner is good!

def not_bad(s):
    f=s.find('not')
    b=s.find('bad')
    if f !=-1 and b!=-1 and b>f:
        s = s[:f]+'good'+s[b+3:]
    return s

print not_bad('This dinner is not that bad!')

輸出結果:

練習五;

Consider dividing a string into two halves.
If the length is even, the front and back halves are the same length.
If the length is odd, we'll say that the extra char goes in the front half.
e.g. 'abcde', the front half is 'abc', the back half 'de'.
Given 2 strings, a and b, return a string of the form
 a-front + b-front + a-back + b-back

def front_back(a, b):
  # +++your code here+++
  # LAB(begin solution)
  # Figure out the middle position of each string.
  a_middle = int(len(a) / 2)
  b_middle = int(len(b) / 2)
  if len(a) % 2 == 1:  # add 1 if length is odd
    a_middle = a_middle + 1
  if len(b) % 2 == 1:
    b_middle = b_middle + 1
  return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]

print front_back('abcde','high')

輸出結果:

練習六:

輸入一個字串列表,
返回同時滿足以下兩個條件的字串的個數:
1.字串長度大等於2
2.字串的第一個字元等於最後一個字元
注:python語言中沒有 ++ 操作符,但是有 += 操作符。
def match_ends(words):
    n = 0
    for i in words:
        new_words=[]
        if i >=2 and i[0]==i[-1]:
            new_words.append(i)
            n+=1
        else:
            pass
    print n
    return new_words
print match_ends(['asdas','dfsafs','ertdsjfhj','fsdsf'])

輸出結果;

練習七:

輸入一個字串列表,
返回滿足以下條件的字串列表:
1.按字母順序從小到大排序
2.第一個字母是'x'的字串排列在最前面
例如:輸入 ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
      返回 ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
提示:可以通過生成兩個列表並對它們分別進行排序,然後再把它們連線起來。
def front_x(words):
    # +++your code here+++
    x_words=[]
    other_words = []
    for w in words:
        if w[0]=='x':
            x_words.append(w)
        else:
            other_words.append(w)
    return x_words + sorted(other_words)

print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])

輸出結果:

練習八:

D. Given a list of numbers, return a list where
all adjacent == elements have been reduced to a single element,
so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
modify the passed in list.

def remove_adjacent(nums):
    result = []
    for i in nums:
        if len(result) == 0 or i != result[-1]:
            result.append(i)
    return result
print remove_adjacent([1, 2, 2, 3])

輸出結果: