Home > OS >  Can anyone help me update this bit of Python 2 code to 3 please?
Can anyone help me update this bit of Python 2 code to 3 please?

Time:12-06

I have inherited a data analysis script written in Python2, which I am trying to update so it runs on Spyder with Python3. When I run the script on Spyder (on MacOS), the following section:

  # Split filename info
                f_split1 = string.split(f,in_delim1) #first pass, splits by ' - '
                f_split2 = string.split(f_split1[0],in_delim2) #second pass, splits by '_'
                sID = f_split2[0]

gives me this error:

AttributeError: module 'string' has no attribute 'split'

I know from reading on StackOverflow that the string bit is obsolete in Version 3, but I am not sure how to update the code and keep the (f,in_delim1) parts.

I'm pretty new to coding and any help updating this is much appreciated. Thanks!

CodePudding user response:

In Python 3, the string module has been removed and its functions, including split(), have been moved to the str type. You can update your code by replacing string.split() with str.split() and remove the import string line at the beginning of your script.

Here's how the updated code might look:

 # Split filename info
f_split1 = str.split(in_delim1) #first pass, splits by ' - '
f_split2 = f_split1[0].split(in_delim2) #second pass, splits by '_'
sID = f_split2[0]

You can also use the rsplit() method instead of split() if you want to split the string starting from the right side instead of the left.

I hope this helps! Let me know if you have any other questions.

  • Related