[英]Remove sub-string from python string after comma
我有一个像这样的python字符串;
input_str = "2548,0.8987,0.8987,0.1548"
我想在最后一个逗号(包括逗号本身)之后的末尾删除子字符串。
输出字符串应如下所示;
output_str = "2548,0.8987,0.8987"
我正在使用python v3.6
split
和join
','.join(input_str.split(',')[:-1])
# Split string by the commas
>>> input_str.split(',')
['2548', '0.8987', '0.8987', '0.1548']
# Take all but last part
>>> input_str.split(',')[:-1]
['2548', '0.8987', '0.8987']
# Join the parts with commas
>>> ','.join(input_str.split(',')[:-1])
'2548,0.8987,0.8987'
rsplit
input_str.rsplit(',', maxsplit=1)[0]
re
re.sub(r',[^,]*$', '', input_str)
如果要多次使用它,请确保编译该正则表达式:
LAST_ELEMENT_REGEX = re.compile(r',[^,]*$')
LAST_ELEMENT_REGEX.sub('', input_str)
您可以尝试这个最简单的方法。 在这里,我们使用split
, pop
和join
来获得所需的结果。
input_str = "2548,0.8987,0.8987,0.1548"
list= input_str.split(",") #Split string over ,
list.pop() #pop last element
print(",".join(list)) #joining list again over ,
假设您的字符串中肯定有一个逗号:
output_str = input_str[:input_str.rindex(',')]
那就是“从字符串的开头到逗号的最后一个索引都应采取所有措施”。
有python 的split函数 :
print input_str.split(',')
将返回 :
['2548,0.8987,0.8987', '0.1548']
但是,如果您有多个逗号, 则在这里使用rsplit :
str = '123,456,789'
print str.rsplit(',', 1)
将返回 :
['123,456','789']
干得好
sep = ','
count = input_str.count(sep)
int i=0;
output = ''
while(i<count):
output += input_str.split(sep, 1)[i]
i++
input_str = output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.