Here is a reusable set of functions that would enable you to more thoroughly understand what it is that you're doing, complete with comments. Perfect for a beginner, if that's the case!
Be mindful, this is a very down and dirty, unpythonic version of what you may be looking for, it is unoptimized. Patrick Haugh and Moses Koledoye both have more simplistic and straight-to-the-point, few-line answers that are extremely pythonic! However, this would be reusable by inputting other lists / arrays as parameters.
My intention for adding this is to help you understand what it is you would be doing by "opening up" the process and going step-by-step.
# Import the regular expressions
import re
# Your list
start = ['foo 1/ bar 2', 'foo 2/ bar 3', 'foo 34/ bar 45']
def hasNumbers(stringToProcess):
""" Detects if the string has a number in it """
return any(char.isdigit() for char in stringToProcess)
def Convert2Tuple(arrayToProcess):
""" Converts the array into a tuple """
# A list to be be returned
returnValue = []
# Getting each value / iterating through each value
for eachValue in arrayToProcess:
# Determining if it has numbers in it
if hasNumbers(eachValue):
# Replace forward slash with a comma
if "/" in eachValue:
eachValue = eachValue.replace("/", ", ")
# Substitute all spaces, letters and underscores for nothing
modifiedValue = re.sub(r"([a-zA-Z_ ]*)", "", eachValue)
# Split where the comma is
newArray = modifiedValue.split(",")
# Turn it into a tuple
tupledInts = tuple(newArray)
# Append the tuple to the list
returnValue.append(tupledInts)
# Return it!
return returnValue
# Print that baby back to see what you got
print Convert2Tuple(start)
You can effectively assign the function to a variable:
finish = Convert2Tuple(start)
So you can access the return values later.
Cheers!