Zoltan Torok
Zoltan Torok

Reputation: 73

Find beginning and end of a string

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.

Upvotes: 0

Views: 1025

Answers (3)

Muhammad Waseem
Muhammad Waseem

Reputation: 13

    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.

Upvotes: 1

NeoMent
NeoMent

Reputation: 176

You can use string slices:

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

Upvotes: 3

user7864386
user7864386

Reputation:

Are you looking for slicing?

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

Output:

pri on gro up bre st 

Upvotes: 3

Related Questions