在python版看到一个小题目: 有以下字符串: IP="189.11.17.1", NM="255.255.0.0", ENTID=1, MCC=460, MNC=3, MSCID="0x36720B", MAXSDB=0, MINUATI24="0x0", MTZDSTS=NO, AIFTYP=TDM, APVER=IOS4.1; 如何获取到各个等号后面的值,保存到一个列表中返回?
我的答案:
- def str_fun():
-
str2 = 'IP="189.11.17.1", NM="255.255.0.0", ENTID=1, MCC=460, MNC=3, MSCID="0x36720B", MAXSDB=0, MINUATI24="0x0", MTZDSTS=NO, AIFTYP=TDM, APVER=IOS4.1;'
-
-
lists = []
-
for tuples in [s.partition('=') for s in str2[:-1].split(',')]:
-
lists.append(tuples[2].strip())
-
print lists
-
-
strs = 'IP="189.11.17.1"'
-
print strs.partition('=')
-
print "the results:"
-
str_fun()
运行结果:
- ('IP', '=', '"189.11.17.1"')
-
the results:
-
['"189.11.17.1"', '"255.255.0.0"', '1', '460', '3', '"0x36720B"', '0', '"0x0"', 'NO', 'TDM', 'IOS4.1']
例2:
- mylist = []
-
strs2 = "123|222|www:rwe"
-
for s in strs2.replace(':', '|').split('|'):
-
mylist.append(s)
-
print mylist
在CU的python版看到一例很典型的,也很隐蔽的bug:
- def strQ2B(ustring):
-
"""把字符串全角转半角"""
-
rstring = ""
-
for uchar in ustring:
-
inside_code=ord(uchar)
-
if inside_code==0x3000:
-
inside_code=0x0020
-
else:
-
inside_code-=0xfee0
-
if inside_code<0x0020 or inside_code>0x7e: #转完之后不是半角字符返回原来的字符
-
rstring += uchar
-
rstring += unichr(inside_code)
-
return rstring
-
-
def strB2Q(ustring):
-
"""把字符串半角转全角"""
-
rstring = ""
-
for uchar in ustring:
-
inside_code=ord(uchar)
-
if inside_code<0x0020 or inside_code>0x7e: #不是半角字符就返回原来的字符
-
rstring += uchar
-
if inside_code==0x0020: #除了空格其他的全角半角的公式为:半角=全角-0xfee0
-
inside_code=0x3000
-
else:
-
inside_code+=0xfee0
-
rstring += unichr(inside_code)
-
return rstring
if -- if -- else 的用法有误。可改成: if -- elif -- else 或者样用continue也可
|