I have a text file which contains a string. In this string there are some numbers which parse out by using regex. After the regex I get this as an output:
0.7.3.4
But lets assume that in another string i get this outout:
0.7.3
In this case I want to ad 00 in the end.
When I do:
lst = get_values.split('.')
print lst[0] -> 0
print lst[1] -> 7
print lst[2] -> 3
print lst[3] -> out of range obviously
So I wanna check if lst[3] is out range, then add "00" to it. Same goes for lst[2] and lst[1]. Here is "dummy pseudo code":
if not lst[3]:
add "00"
The end output should look like this in the end:
070304
or maybe like this is a lst[x] is missing:
070300
And the first "0" is also removed just in case you wonder where it was.
答案 0 :(得分:1)
这可能对您有用:
def format_string(str):
parts = [0, 0, 0]
for idx, num in enumerate(str.split('.')[1:]):
parts[idx] = int(num)
return '%02d%02d%02d' % tuple(parts)
print(format_string('0.7.3.4'))
print(format_string('0.7.3'))
输出:
070304
070300
如果您想让它更具可定制性:
def format_string(str, expected_parts=3, ignore_parts=1):
input_parts = str.split('.')[ignore_parts:]
output_parts = ['00'] * expected_parts
for idx, num in enumerate(input_parts):
output_parts[idx] = '%02d' % int(num)
return ''.join(output_parts)