我有这个字符串:
"I have been working - 8h by day"
"Like - 9H by Month"
我正在努力获得小时数。基本上我正试图得到这个输出:
8
9
我尝试了这个但没有成功:
print(myString.split("H",1)[1] )
但我得到了这个:
builtins.IndexError: list index out of range
如何在Python中“ - ”之后和“H”之前获取字符串?
谢谢!
答案 0 :(得分:1)
你遇到的问题是"I have been working - 8h by day"
中没有"H"
,所以当你用“H”分割时,列表中只有一个元素。
你可以使用正则表达式找到它
import re
pattern = r'\d(?=[h|H])'
data = ["I have been working - 8h by day",
"Like - 9H by Month"]
for item in data:
print re.findall(pattern, item)
答案 1 :(得分:0)
使用正则表达式
<强>实施例强>
import re
s = ["I have been working - 8h by day", "Like - 9H by Month"]
for i in s:
print(re.findall("\d+H" ,i, flags=re.I))
<强>输出:强>
['8']
['9']
答案 2 :(得分:0)
只有在re.findall
或h
跟着后才能使用H
匹配所有数字:
import re
s = ["I have been working - 8h by day", "Like - 9H by Month"]
new_s = [re.findall('\d+(?=H)', i, flags=re.I)[0] for i in s]
输出:
['8', '9']
答案 3 :(得分:0)
这有一个危险,它将在其他Hs上分裂,并且它保留整个字符串(为了解决这个问题,用正则表达式写出更好的表达式)。
按原样解析您的代码:
$(document).ready(function() {
$(".case").change(function(){
if(this.checked) { // this = the current checkbox clicked
var index = $(this).parent().index();
var childrenAmt = $('#table tr').length;
var array = [];
for(var i = 1; i < childrenAmt; i++) {
var data = $('#table tr').eq(i).children()[index].innerHTML;
array.push(data);
}
console.log(array);
// return array // Do as you please with the values
}
});
});