Please tell me what you think of this its my first try and I have only been learning Python for 3 days now, works with both 'index' and 'find':
data = ["XBOX 360 | 150 | New",
"PlayStation 3 | 35 | Broken",
"Windows 8 | 275 | New"]
Id = 0
one = data[Id].index("|")
two = data[Id].index("|", one+1)
product = data[Id][:one]
price = data[Id][one+2:two]
condition = data[Id][two+2:]
print(product)
print(price)
print(condition)
#Just add more like these:
#three = data[Id].index("|", two+1)
#four = data[Id].index("|", three+1)
#etc... If you want to add more 'Pipes'
#Add one to each 'pipe' no more then that or you'll get an error
#You can add as many new 'data' items as you want
#just change the 'Id' to view them
2 Answers 2
First, there is no need to use index()
method for finding the position of next and next delimiter (and then use it for slicing) - Python is able to split the string at a higher level - pinpoint the delimiter and then use the split()
method:
DELIMITER = " | " # we will use it for splitting the string
"XBOX 360 | 150 | New".split(DELIMITER) # the result will be ["XBOX 360", "150", "New"]
As you may see from the comment, the result is a list of individual parts.
Second - so we now have the list of the appropriate parts of the string.
Let give it the name parts
- so parts
will be the list:
["XBOX 360", "150", "New"]
(You may obtain it by the command parts = data[0].split(DELIMITER)
in your code.)
Now instead of using indices for getting individual parts, i. e. "XBOX 360"
, "150"
, and "New"
:
product = parts[0]
price = parts[1]
condition = parts[2]
you may just unpack the parts
list:
product, price, condition = parts
Third, fourh, fifth, ... - I'm not going to overload you :-)
You are doing things the hard way, there is a python function to cut up strings namely the .split()
method
Thus to make it easier to use and more general I can rewrite your code like this:
data = ["XBOX 360 | 150 | New",
"PlayStation 3 | 35 | Broken",
"Windows 8 | 275 | New"]
# Here I loop through the data
# Thus I read each row starting with the XBOX360 line and ending at Windows 8
for row in data:
# Use .split() to split the string with a specific char(set)
product_info = row.split(' | ')
# Tuple unpacking
product, price, condition = product_info
# Use pretty formatting
print ('\nProduct: {}'.format(product))
print ('Price: {}'.format(price))
print ('Condition: {}'.format(condition ))
Try it out for yourself to see the difference, and if unclear what is going on you can always ask me
-
\$\begingroup\$
[ [ print(word.strip) for word in row.split()] for row in data]
\$\endgroup\$Erich– Erich2017年08月30日 17:01:12 +00:00Commented Aug 30, 2017 at 17:01