Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting on / inside a list in Python

Tags:

python

I've got a list that contains the following:

x = ['1', '2/keys', '3']

Now the '2/keys' must be splitted. I figured it should be possible to make a list in a list? But before splitting, I've got to check if there's a "/" at all.

The following code, that obviously doesn't work, is what I've got:

for numbers in x:
            if '/' in x:
                x[numbers].split('/')

Is it possible to have an outcome like:

x = ['1', ['2', 'keys'], '3']
like image 607
12th Avatar asked May 13 '19 13:05

12th


People also ask

How do you separate items in a list?

Usually, we use a comma to separate three items or more in a list. However, if one or more of these items contain commas, then you should use a semicolon, instead of a comma, to separate the items and avoid potential confusion.

Can you use the split function with a list?

A split function is composed of a specified separator and max parameter. A split function can be used to split strings with the help of a delimiter. A split function can be used to split strings with the help of the occurrence of a character. A split function can be used to split strings in the form of a list.


1 Answers

You are very close.

x = ['1', '2/keys', '3']
for ind, numbers in enumerate(x):
    if '/' in numbers:
        x[ind] = numbers.split('/')
print(x)

Or a list comprehension

Ex:

x = [numbers.split('/') if '/' in numbers else numbers for numbers in x]
like image 179
Rakesh Avatar answered Nov 14 '22 23:11

Rakesh