1

I have a list in python:

name = ['A.A.BCD', 'B.B.AAD', 'B.A.A.D']

I wish to discard everything before the second '.' and keep the rest. Below is what I have come up with.

[n.split('.')[2] for n in name]

Above is working for all except the last entry. Any way to do this:

Expected output: ['BCD', 'AAD', 'A.D']

2 Answers2

2

Read the documentation for split() and you’ll find it has an optional parameter for the maximum number of splits - use this to get the last one to work:

[n.split('.',maxsplit=2)[2] for n in name]

See https://docs.python.org/3/library/stdtypes.html?highlight=split#str.split

Big disadvantage of doing this as a one-liner is it will fail if there ever aren’t two . in a string, so using a for loop can be more robust.

1
name = ['A.A.BCD', 'B.B.AAD', 'B.A.A.D']
['.'.join(n.split('.')[2:]) for n in name]

result

['BCD', 'AAD', 'A.D']
wrxue
  • 158
  • 6