同一行代码中的多个拆分?

时间:2015-09-21 20:42:28

标签: python python-2.7

我试图转换这个: /bcs/lgnp/clientapp/csvbill/audit_process/inwork_20150921141500/LGNP.SMR.CSV0000.BILL.INPUT01.kb01^^.20150921140115.xml

对此: kb01^^.20150921140115

目前我通过以下方式实现这一目标:

cur_file = '/bcs/lgnp/clientapp/csvbill/audit_process/inwork_20150921141500/LGNP.SMR.CSV0000.BILL.INPUT01.kb01^^.20150921140115.xml'
file_path = cur_file.split('/')
file_name = file_path[-1].split('.')
project_code = file_name[5] + '.' + file_name[6]

可以一步完成吗?

5 个答案:

答案 0 :(得分:2)

类似这样的事件NotificationCompat.Builder notification; private static final int unid = 6546468; notification = new NotificationCompat.Builder(this); notification.setAutoCancel(true); notification.setSmallIcon(R.drawable.ic_stat_name); notification.setTicker(nickname + " : " + message); notification.setWhen(System.currentTimeMillis()); notification.setContentTitle(nickname); notification.setContentText(message); notification.setDefaults(Notification.DEFAULT_SOUND); Intent shoutbox = new Intent(this, Shoutbox.class); Random randomGenerator = new Random(); int randomInt = randomGenerator.nextInt(100); PendingIntent pshoutbox = PendingIntent.getActivity(this, randomInt, shoutbox, PendingIntent.FLAG_CANCEL_CURRENT); notification.setContentIntent(pshoutbox); notification.setLights(Color.BLUE, 1500, 500); long[] pattern = {500,500}; NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.notify(unid, notification.build());

答案 1 :(得分:1)

您的代码在一行:

project_code = '.'join(curr_file.split('/')[-1].split('.')[-3:-1])

因为split()函数返回一个字符串列表,你可以立即使用地址string.split()[n],这只是另一个字符串,这样你就可以应用string.split()[].split()[]直到你到达那里你想成为。

这就是上面所做的。最后[-3:-1]只是最后的索引,始终删除.xml

'.'.join()是一种将句号放回来的方式,同时也使结果成为一个字符串。

由于split('/')之后没有理由split('.'),您可以将其缩短为:

project_code = '.'join(curr_file.split('.')[-3:-1])

祝你好运,编码愉快!

答案 2 :(得分:1)

路径拆分也可以使用os.path.basename(cur_file)完成(import os.path cur_file = '/bcs/lgnp/clientapp/csvbill/audit_process/inwork_20150921141500/' +\ 'LGNP.SMR.CSV0000.BILL.INPUT01.kb01^^.20150921140115.xml' print '.'.join(os.path.basename(cur_file).split('.')[5:7]) 返回路径的文件名部分):

.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

答案 3 :(得分:1)

s="/bcs/lgnp/clientapp/csvbill/audit_process/inwork_20150921141500/LGNP.SMR.CSV0000.BILL.INPUT01.kb01^^.20150921140115.xml"

print(s.split(".",5)[-1].rsplit(".",1)[0])

如果您知道最后要删除4个字符:

print(s.split(".",5)[-1][:-4])

或者:

print(".".join(s.rsplit(".",3)[1:-1]))

或者使用str.format和unpacking:

print("{}.{}".format(*s.rsplit(".", 3)[1:]))

如果任何字符串不是您发布的格式,则此答案和其他所有答案很可能都会失败。

答案 4 :(得分:0)

我将向您介绍正则表达式的强大功能,但不要担心,他们随时为您提供帮助。

如果没有事先了解其他路径的样子,我们可以假设项目代码是路径的最后一位,它由两个点之间的任意字符串和一个点之间的一系列数字组成。扩展,所以捕获这个的正则表达式将是:

import re
exp = re.compile(ur'.+\.(.+\.\d+).xml')

然后你可以使用那个编译的正则表达式在你的字符串中找到匹配的标记,只需一行:

project_name = re.findall(exp, cur_file)[0]
相关问题