DEV Community

Phondanai
Phondanai

Posted on

1 1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay