DEV Community

Phondanai
Phondanai

Posted on

Bite-Size Python: String

Python have many, useful functions to work with string. This post I will demonstrate some functions I frequently use.

Let's start!

split : Splitting a string using space as delimiter by default and return a list

>>> paragraph = "Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991."
>>> word_list = paragraph.split()
>>> word_list
['Python',
 'is',
 'an',
 'interpreted,',
 'high-level,',
 'general-purpose',
 'programming',
 'language.',
 'Created',
 'by',
 'Guido',
 'van',
 'Rossum',
 'and',
 'first',
 'released',
 'in',
 '1991.']
# You can change delimiter too 
>>> word_list_split_by_comma = paragraph.split(',')
>>> word_list_split_by_comma
['Python is an interpreted',
 ' high-level',
 ' general-purpose programming language. Created by Guido van Rossum and first released in 1991.']

join : Combine list of string to single string with custom delimeter

>>> word_list
['Python',
 'is',
 'an',
 'interpreted,',
 'high-level,',
 'general-purpose',
 'programming',
 'language.',
 'Created',
 'by',
 'Guido',
 'van',
 'Rossum',
 'and',
 'first',
 'released',
 'in',
 '1991.']
>>> "|".join(word_list)
'Python|is|an|interpreted,|high-level,|general-purpose|programming|language.|Created|by|Guido|van|Rossum|and|first|released|in|1991.'
# OR
>>> "|".join(paragraph.split())
'Python|is|an|interpreted,|high-level,|general-purpose|programming|language.|Created|by|Guido|van|Rossum|and|first|released|in|1991.'

Slicing : You can slice string as same as list.

>>> first_25_chars = paragraph[:25]
first_25_chars
'Python is an interpreted,'
>>> last_25_chars = paragraph[-25:]
>>> last_25_chars
'd first released in 1991.'
>>> reverse_paragraph = paragraph[::-1]
>>> reverse_paragraph
'.1991 ni desaeler tsrif dna mussoR nav odiuG yb detaerC .egaugnal gnimmargorp esoprup-lareneg ,level-hgih ,deterpretni na si nohtyP'

len & count: string length & counting occurrence sub string

>>> len(paragraph) # This can tell how many index we can use when slicing
131
>>> paragraph.count("ed")
6

For fun

Use center to centering your text, with amount of supply width spaces and custom character replacement rather than space.

>>> "TADA!".center(30, "🌈")
'🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈TADA!🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈'

Thank you for reading :)

References

Top comments (0)