替换字符串中的日期字符:Python replace与re.sub方法实操
replace() and re.sub() to Adjust '2018' Dates Hey there! Let’s walk through exactly what happens when you use either the string replace() method or re.sub() to swap '2018' with '2018-' in your comma-separated date string, plus how each method works under the hood.
1. Using the String Built-in replace() Method
Code Example
# Your original date string date_str = '20180101,20180102,20180103,...,20180208' formatted_str = date_str.replace('2018', '2018-')
What It Does
Running this will transform every occurrence of the substring 2018 in your input to 2018-. So each date entry like 20180101 becomes 2018-0101, resulting in a string that looks like this:
'2018-0101,2018-0102,2018-0103,...,2018-0208'
How It Works
The replace() method is a straightforward literal substring replacer. It scans the entire string from left to right, finds every non-overlapping instance of the first argument (2018), and swaps it with the second argument (2018-). Since all your dates start with 2018 and there are no other instances of 2018 in the string, this hits every date exactly once—no extra or missing replacements here.
2. Using re.sub() from the re Module
Code Example
import re # Your original date string date_str = '20180101,20180102,20180103,...,20180208' formatted_str = re.sub('2018', '2018-', date_str)
What It Does
For your specific input string, the output is identical to the replace() method: every 2018 becomes 2018-, turning your dates into 2018-0101, 2018-0102, etc.
How It Works
re.sub() is the regular expression substitution function. In this case, we’re using a literal regex pattern (2018)—no special regex characters, so it behaves almost exactly like replace(). The regex engine searches the string for all matches of the pattern (again, non-overlapping) and replaces each with the specified string.
The main advantage of using re.sub() here would be if your date string had more complex patterns (like mixed years, or 2018 appearing in other contexts). For example, you could use a pattern like r'\b2018' to only match 2018 that starts a word (so it doesn’t replace 2018 if it’s part of a longer number). But for your current input, both methods do the same job.
Quick Note
It’s important to mention that both methods only add a dash after the year—they don’t split the month and day into separate parts (like turning 2018-0101 into 2018-01-01). If you wanted that full ISO date format, you’d need a different approach (like using regex to capture year, month, and day groups), but that’s beyond the scope of the two methods you asked about.
内容的提问来源于stack exchange,提问作者sunspots

