5 Quick Tips To Manage Your Strings In Python

Master the basics of Python

This post will be a very practical one, providing you with simple and quick tips to work with strings in Python.

String multiplication

Python allows multiplying not only numbers, but also strings! Repeat a string as simply as follows:

>>> "a"*3
'aaa'
>>>

You may also multiply strings by a boolean value. For instance, the following snippet pads a number with a leading zero if it’s lower than 10:

>>> sn = lambda n: '{}{}'.format('0' * (n < 10), n)
>>> sn(9)
'09'
>>> sn(10)
'10'
>>>

Title

Nowadays, it’s common to write titles (even in Medium), capitalizing the first letter of each word. Well, you can achieve this very easily with Python:

>>> "the curious frog went to denmark".title()
'The Curious Frog Went To Denmark'
>>>

Concatenate

You may concatenate two strings using the + operator, but that’s not the best approach. Python strings are immutable, making this operator create a new string from these two strings, instead of simply adding the second one to the first one, as we could have thought. It’s better (and faster), instead, to concatenate them using the join() function:

>>> "".join(["abc", "def"])
'abcdef'
>>>

Slicing

Obtain a substring using Python’s slicing. You just need to specify the starting index (included) and the ending index (excluded):

>>> "Such a good day"[7:11]
'good'
>>>

Reverse a string

A string slicing allows you to optionally define a third parameter: the step. If you take the full string and apply a step of -1, you’ll get the reversed string:

>>> "Such a good day"[::-1]
'yad doog a hcuS'
>>>

That’s it! Visit Python’s string documentation to learn more.

我来评几句
登录后评论

已发表评论数()

相关站点

热门文章