Home > OS >  Check the string is ending with "|" using python
Check the string is ending with "|" using python

Time:12-26

I need to check whether the string ends with | or not.

Student,"Details"
Joe|"December 2017|maths"
Bob|"April 2018|History|Biology|Physics|"
sam|"December 2018|physics"

I have tried with the below code and it's not working as expected.

def Pipe_in_variant(path):
    df = pd.read_csv(path, sep='|')
    mask = (df['Details'])
    result = mask.endswith(""|"")
    print("...................")
    print(result)

CodePudding user response:

Your example input is unclear, however assuming you want to check is items in a column end with something, use str.endswith.

Example:

df = pd.DataFrame({'Details': ['ab|c', 'acb|']})

df['Details'].str.endswith('|')

output:

0    False
1     True
Name: Details, dtype: bool
printing the matching rows:
df[df['Details'].str.endswith('|')]

output:

  Details
1    acb|

CodePudding user response:

Note - I think first row of input should be Student|"Details" instead of Student,"Details".

Here is what you can do

import pandas as pd
dframe = pd.read_csv('input.txt', sep='|')
dframe['ends_with_vbar'] = dframe['Details'].str.endswith('|')
dframe

Output:

  Student                              Details  ends_with_vbar
0     Joe                  December 2017|maths           False
1     Bob  April 2018|History|Biology|Physics|            True
2     sam                December 2018|physics           False

Then you can print the marked row as follows

for _, row in dframe[dframe['ends_with_vbar']].iterrows():
    print(f'{row["Student"]} - {row["Details"]}')

Output:

Bob - April 2018|History|Biology|Physics|
  • Related