-1

I want to extract next part (from '-') of the file name which is 000.xyz. [file name is Axx-000.xyz]

so my friend showed me this code but I couldn't understand the code fully.

def get_rank(xyz):                       
    pref = xyz.split('-')[1]             
    pref = pref.replace('.xyz', '')     
    return pref

I expect the code will show the result as Axx-000.xyz should be 000 or 000.xyz

Many thanks in advance.

hiro protagonist
  • 40,708
  • 13
  • 78
  • 98
DGKang
  • 163
  • 12

2 Answers2

3

So, here is the explanation of this function, line by line.

pref = xyz.split('-')[1]: This line can be split in the following two lines:

  1. split_string = xyz.split('-')
  2. pref = split_string[1]

The first line means "look at the string and cut it wherever you find the character '-'. For example, for the string "Axx-000.xyz", the character is found once and splitted_string will be a list of 2 strings: ["Axx","000.xyz"].

The second line means "put in pref the second element of the list split_string.

Then the line pref = pref.replace('.xyz', '') call the method replace, which means: "look at the string and wherever you find the string '.xyz', replace it by '' (so nothing).

So the value returned by the function contains the second element of the table ["Axx","000.xyz"] without '.xyz', so simply 000.

1

You define python function using def, inside of brackets there are argument of function that you define while calling it (e.g. get_rank("Axx-000.xyz")).

pref = xyz.split('-')[1] here you splitting xyz string by - and assigning splitted elements into array. pref variable gets value of index [1] of that array (second value).

pref = pref.replace('.xyz', '') here you simply replacing '.xyz' phrase with nothing '', otherwords you erasing .xyz from string.

On the last line you get final result - 000 string.

Mitrundas
  • 11
  • 4