-1

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

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

If I try get_rank('Axx-000.xyz') which will return 000.

I just started python lang I just want to clarify whether what I think how it works is correct or not.

So the first line of the function will split the string to list of strings.

  1. if I do get_rank('Axx-000.xyz') 'Axx-000.xyz' will turn into
    ['Axx', '000.xyz'] then store 1st order element (000.xyz) as pref
  2. the second line will replace/erase the string (.xyz) to nothing. so pref = 000

Is this correct process of the function?

DGKang
  • 172
  • 1
  • 13

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.

Damien Cappelle
  • 178
  • 1
  • 8
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