关于字符串的应用

时间:2022-07-25
本文章向大家介绍关于字符串的应用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.判断字符串是否为小数

try:
    lat = float(location.split(',')[1])
    lon = float(location.split(',')[0])
except ValueError:
    print('no number')

2.用split对字符串进行分割

str='storeId=ff8080816277aa0a0162845d48e3012b&appid=wxe37b2e703155ed41&transId=wxe37b2e703155ed412019-05-09%2010%3A28%3A15&sign=dc8fac903b03556247659e1b548bccce&timestamp=2019-05-09%2010%3A28%3A15&memberId=ff8080816a889e71016a9a68a6c55a37&cliqueId=-1&cliqueMemberId=-1&useClique=0&enterpriseId=ff808081624e60f601625c50a30900ce&unionid=oLWn80pR0DtSJXfnO_1O4ZOzfvAE&openid=oZe8D5gmPcPANw4kNNcG8mlAW1mI&launchOptions=%7B%22path%22%3A%22%2Fpages%2Fmall%2Fmall-index%2Fmall-index%22%2C%22query%22%3A%7B%7D%2C%22scene%22%3A1102%2C%22referrerInfo%22%3A%7B%22appId%22%3A%22wx97e5123eb6041454%22%7D%7D'

str2=str.split('&')

for i in str2:
    print('"'+i.split('=')[0]+'":"'+i.split('=')[1]+'",')

结果如下:

"storeId":"ff8080816277aa0a0162845d48e3012b",
"appid":"wxe37b2e703155ed41",
"transId":"wxe37b2e703155ed412019-05-09%2010%3A28%3A15",
"sign":"dc8fac903b03556247659e1b548bccce",
"timestamp":"2019-05-09%2010%3A28%3A15",
"memberId":"ff8080816a889e71016a9a68a6c55a37",
"cliqueId":"-1",
"cliqueMemberId":"-1",
"useClique":"0",
"enterpriseId":"ff808081624e60f601625c50a30900ce",
"unionid":"oLWn80pR0DtSJXfnO_1O4ZOzfvAE",
"openid":"oZe8D5gmPcPANw4kNNcG8mlAW1mI",
"launchOptions":"%7B%22path%22%3A%22%2Fpages%2Fmall%2Fmall-index%2Fmall-index%22%2C%22query%22%3A%7B%7D%2C%22scene%22%3A1102%2C%22referrerInfo%22%3A%7B%22appId%22%3A%22wx97e5123eb6041454%22%7D%7D",

3.检测字符串乱码

import chardet
f=open('test.txt','rb')
f_read=f.read()
f_charInfo=chardet.detect(f_read)
print(f_charInfo)
# f_charInfo的输出是这样的的一个字典{'confidence': 0.99, 'encoding': 'utf-8'}

4.将逗号分隔的字符串转换为列表

给定一个字符串: 它是由逗号分隔的几个值的序列:

mStr = '192.168.1.1,192.168.1.2,192.168.1.3' 

如何将字符串转换为列表?

mStr = ['192.168.1.1', '192.168.1.2', '192.168.1.3']
  • 使用str.split方法:
>>> mStr = '192.168.1.1,192.168.1.2,192.168.1.3'
>>> mStr.split(",")
['192.168.1.1', '192.168.1.2', '192.168.1.3']
  • 将字符串转成元组:
>>> mlist = mStr.split(",")
>>> tuple(mlist)
('192.168.1.1', '192.168.1.2', '192.168.1.3')

5.两个列表的各项分别合并为列表

[ [a,b] for a,b in zip(list1,list2)]

生成一个以列表list1,list2各项合并列表为元素的列表