繁体   English   中英

在python中正确拆分字符串

[英]Split properly a string in python

我有以下字符串:

string = ' 1234 91 1404 '

我想以这种方式拆分,以便最终输出为: 1234,91,1404 有没有简单的方法来做到这一点? 我尝试了splitjoin命令但没有成功。

s = '  1234      91          1404  '
output = ','.join(s.split())
print(output)

输出

1234,91,1404

以正确的方式做到这一点:

string = '  1234      91          1404  '
print (','.join(string.split()))

输出:

1234,91,1404

您也可以使用正则表达式。 我提供了一种不同的方法, join()split()可能更有效:

import re
string = '  1234      91          1404  '
string = ','.join(re.findall(r'(\d+)', string))

谢谢指出!

print ",".join(s.split())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM