Python Library Tips: strip off letter from list


f.strings

In this series of posts , learn how to use Python Library functions

How to strip off no of letters from a list of strings

The split function of string class can be used to split words from a string. do you know how to creating a abbreviated set of strings from a list. I

With a comprehension statement in Python this can’t be hard

list=['PYTHON','CPYTHON','IPYTHON']
stripped=[ k[:3] for k in list]
print(stripped)
['PYT', 'CPY', 'IPY']

Here we strip of the each list element using : operator in the list and specify the number of characters want to keep.

You can also have the reverse order using k[3:] or can use the starting and ending position as follows

stripped=[ k[0:4] for k in list]
print(stripped)
#['PYTH', 'CPYT', 'IPYT']

stripped=[ k[1:4] for k in list]
print(stripped)
#['YTH', 'PYT', 'PYT']

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.