无需正则表达式,优雅修改下划线分隔文件名指定字段的方法
Got it, let's fix this without messy repeated splits or regex. The key is to split the filename strategically only where we need to, then reconstruct it cleanly.
Approach 1: Split on the last underscore (most concise)
Since your target field is the last segment before the file extension, we can split the filename once at the final underscore to separate the prefix from the target+suffix part. Then we just replace the target part and rejoin:
frameNumber = "&example" # Your replacement string here image_name = "centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg" # Split into prefix (everything before last underscore) and target+suffix prefix, target_with_suffix = image_name.rsplit('_', 1) # Extract the file extension (e.g., .jpg) _, suffix = target_with_suffix.split('.', 1) # Build the new filename new_name = f"{prefix}_{frameNumber}.{suffix}"
This gives you exactly the format you want: centerOne_camera_2_2018-04-11_15:11:21_&example.jpg
Approach 2: Split all segments and replace the target index
If you prefer working with all the underscore-separated parts explicitly, you can split once, replace the specific segment, then rejoin. This is great if you might need to modify other segments later:
frameNumber = "&example" image_name = "centerOne_camera_2_2018-04-11_15:11:21_2.0.jpg" parts = image_name.split('_') # Extract the suffix from the last part suffix = parts[-1].split('.')[1] # Replace the target segment (the one containing 2.0) with your new string + suffix parts[-1] = f"{frameNumber}.{suffix}" # Rejoin all parts with underscores new_name = '_'.join(parts)
Why this is better than your original approach
- No repetitive
split('_')calls (which are inefficient and hard to read) - Uses proper string joining with underscores (so you don't end up with concatenated text like
centerOnecamera2...) - Dynamically extracts the file extension instead of hardcoding it (works for .png, .jpeg, etc., too)
内容的提问来源于stack exchange,提问作者deadcode

