Home > front end >  Find beginning and end of a string
Find beginning and end of a string

Time:02-21

Lets say I have a list of words called "words" and want to print either what they begin or end with with the functions endch and begch, something like this:

words = ["prison", "group", "breakfast"]
for i in words:
  print(i.begch(3))
  print(i.endch(2))

This would result in showing: pri on gro up bre st.

Which function / code does that (I want something better than getting characters one by one from start or end and concatenating them) ? "str.startswith" requires you to already know the prefix you're looking for and prefix finding functions find the prefix common for all words.

CodePudding user response:

Are you looking for slicing?

for i in words:
    print(i[:3], i[-2:], end=' ')
    

Output:

pri on gro up bre st 

CodePudding user response:

You can use string slices:

words = ["prison", "group", "breakfast"]
for i in words:
    print(i[:3], i[-2:])

CodePudding user response:

    def begch(str, idx):
        return str[ : idx]
    def endch(str, idx):
        return str[-idx : ]
    words = ["prison", "group", "breakfast"]
    for i in words:
        print(begch(i,3))
        print(endch(i,2))

I hope this is what you are looking for.

  • Related