user1869582
user1869582

Reputation: 459

find and replace a character in my file names with a python re

basically I want to change the first "." to "_" Name.1001.ext to Name_1001.ext:

I have something like this but it is returning the original name:

print re.sub(r'\D+.\d+\.$',r'\D+_\d+\.$',fileName)

Upvotes: 1

Views: 734

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

Regex seems like an overkill for this example, you should probably go for str.replace() here:

In [16]: strs="Name.1001.ext"

In [17]: strs.replace(".","_",1) # now only 1 occurrence of the 
                                 # substring is going to be replaced 
Out[17]: 'Name_1001.ext'

S.replace(old, new[, count]) -> string

Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Upvotes: 5

Related Questions