Python字符串操作

今天做newcode的‘直方图内最大矩形’的问题,坑爹了字符串操作折腾了好久,特地来总结下。题目为(http://www.nowcoder.com/practice/13ba51c3fec74b58bbc8fa8c3eedf877?tpId=49&tqId=29284&rp=1&ru=/ta/2016test&qru=/ta/2016test/question-ranking)

先把代码贴上来,本机Python3.4跑的结果没问题,newcoder是Python2.7的,报错,还没解决:%d format: a number is required, not NoneType

# -*- coding:utf-8 -*-

class MaxInnerRec:
    def countArea(self, A, n):
        # write code here
        l = []
        for ii in range(n - 1, 0, -1):
            for jj in range(0, ii):
                if A[jj] > A[jj + 1]:
                    # tmp = A[jj]
                    # A[jj] = A[jj + 1]
                    # A[jj + 1] = A[jj]
                    A[jj],A[jj + 1] = A[jj + 1],A[jj]

        print (A)                   #排序完成后
        for i in range(n):
            l.append(A[i] * (n - i))    #计算面积



        for ii in range(n):
            if l[0] < l[ii]:
                l[0], l[ii] = l[ii], l[0]
        print(l)                    #对面积排序

        print(l[0])


if __name__ == "__main__":

    A = []
    ss = input()
    aa = ss.replace('[',' ')
    aa = aa.replace(']',' ')
    aa = aa.split(',')
    n = int(aa[-1])
    for i in range(int(aa[-1])):
        A.append(int(aa[i]))
    print(A)

    # A = [2,7,9,4,1]
    # n = 5

    ch = MaxInnerRec()
    ch.countArea(A,n)


正文:字符串操作

replace:字符串替代
ss = [2,7,9,4,1]
aa = ss.replace('[',' ')  #ss字符串中所有的'['用' '空格代替 
aa =  2,7,9,4,1]
split:字符串分割
    A = ‘2,7,9,4,1’      #A为一个字符串    
    aa = aa.split(',')    #用,分割A,使A成为一个string类型的list
split有多个分割符时,就要用到正则表达式了:
import re
s1 = [8,4,6,2,5,9,1],7

s2=re.split(r'[\[\s\]\,]+',s1) #去掉[、空格、],+表示多个符号
print (s2)

['', '8', '4', '6', '2', '5', '9', '1', '7']    #为什么前面有个空格,去不掉

 

join:字符串连接
a = ['a','b','c','d']           #a[1]='a',a[-1]='d'
content = ''.join(a)
print content

abcd
下次再添加。。

 


 


 


 

posted @ 2016-08-15 19:42  航飞冲天  阅读(302)  评论(0编辑  收藏  举报