yangyang
yangyang

Reputation: 531

How can I split a string and take only one from the separated string in Python?

I have a string which includes ":", it shows like this:

: SHOES

and I want to split the colon and SHOES, then make a variable that contains only "SHOES"

I have split them used df.split(':') but then how should I create a variable with "SHOES" only?

Upvotes: 1

Views: 1710

Answers (4)

Rubén
Rubén

Reputation: 44

You can use 'apply' method to execute a loop over all dataset and split the column with 'split()'.

This is an example:

import pandas as pd

df=pd.DataFrame({'A':[':abd', ':cda', ':vfe', ':brg']})

    # First we create a new column just named a new column -> df['new_column']
    # Second, we loop dataset with apply
    # Third, we execute a lambda with split function, getting only text after ':'
df['new_column']=df['A'].apply(lambda x: x.split(':')[1] )

df
        A   new_column
0   :abd    abd
1   :cda    cda
2   :vfe    vfe
3   :brg    brg

Upvotes: 2

Sergio Rodriguez
Sergio Rodriguez

Reputation: 8658

Here is a small working sample. Both stripValue and newString return the same value. It is matter cleaner code vs verbose code:

    # set initial string
    myString = "string : value"
    
    # split it which will return an array [0,1,2,3...]
    stripValue = myString.split(":")

    # you can create a new var with the value you want/need from the array
    newString = (stripValue[1])
    
    # or you can short hand it
    print(stripValue[1])
    
    # calling the new var
    print(newString)

Upvotes: 0

Philipnah
Philipnah

Reputation: 1

If your original strings always start with ": " then you could just remove the first two characters using:

myString[2:]

Upvotes: 0

Yash
Yash

Reputation: 1281

You can use the list slicing function. and then use lstrip and rstrip to remove excess spaces before and after the word.

df=": shoes"
d=df.split(":")[-1].lstrip().rstrip()
print(d)

Upvotes: 2

Related Questions