r/pythontips • • Sep 23 '21

Data_Science 15 Must-Know Python String Methods

Python is a great language. It is relatively easy to learn and has an intuitive syntax. The rich selection of libraries also contribute to the popularity and success of Python. Visit here: https://www.thinkdataanalytics.com/python-string-methods/

41 Upvotes

5 comments sorted by

14

u/boojieboy Sep 23 '21

These are all pretty elementary methods, and I think a person learns them almost by osmosis if you do any project that involves some degree of text processing.

For me, the must-know string methods--the ones that will do the most for levelling up your skills--are those methods involving regular expressions.

Each language has its own way of implementing them, but they are always and without exception sueprcharged shortcuts to accomplishing fast, concise, high throughput find/replace algos

3

u/expressadmin Sep 23 '21

Would somebody give an example as to when you would want to use partition? I've heard of it before but never seen it used and struggle to think of a use case where I would use it.

5

u/[deleted] Sep 23 '21

I have had a bulky coin/pair csv files. Tons of exchange names (FTX,BINANCE etc.) and pairs (BTC/USDT etc.) .

BINANCE  :  BTC/USDT,ETH/USDT,LTC/USDT,NEO/USDT,BTC/USDT....
BITFINEX :  BTC/USD,ETH/USD,LTC/USD,AID/USD,BAT/USD,BTC/USD....

And these strings contains 2 part. Spot and futures. But while I was scraping forgot to separate them and results were confusing. I had 2 same pair at each exchange? So I had to split them. And I tought I could easily separate them to tuple. End of the script I get results like this:

BINANCE  : SPOT-> .... , FUTURES-> ....
BITFINEX : SPOT-> .... , FUTURES-> ....

I hope it is clear. Have a nice day!

2

u/oohay_email2004 Sep 24 '21

I was hitting an FTP server for file modification times and it didn't support the newer way to get them. str.partition is one way to parse the response, could also go with str.split(' ', maxsplit=1)

From memory:

response = ftp.voidcmd(f'MDTM {filename}')
code, _, string = response.partition(' ')
if code != '213':
    # do stuff with error, `string` is an 
    # error message that may contain spaces.
else:
    # parse `string` as datetime and continue

1

u/AnonymouX47 Sep 25 '21 edited Sep 25 '21

May be okay for a newbie but i feel this is pretty basic and not including the right-hand counterparts of methods like find(), split(), partition() (i.e rfind(), etc...) even make it worse.

Also, the methods covered have more useful functionality...