Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

string python

This article discusses 31 essential built-in string methods in Python, providing examples and explanations for each method. It covers various operations such as slicing, stripping, replacing, and formatting strings, which are crucial for effective string manipulation in programming. The resource aims to equip readers with the knowledge needed to work with strings efficiently.

Uploaded by

Abhay Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

string python

This article discusses 31 essential built-in string methods in Python, providing examples and explanations for each method. It covers various operations such as slicing, stripping, replacing, and formatting strings, which are crucial for effective string manipulation in programming. The resource aims to equip readers with the knowledge needed to work with strings efficiently.

Uploaded by

Abhay Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

31 essential String methods in Python you should

know

In this article we learn about the most essential built-in string methods.

Patrick Loeber · · · · ·
December 19, 2021 · 14 min read

Python Basics

31 ESSENTIAL Python String Methods

Strings are an essential data type in Python that are used in nearly every application. In this article
we learn about the most essential built-in string methods.

With this resource you will be equipped with all the tips and knowledge you need to work with
strings easily and you will be able to modify them without any problems.

1. Slicing
With slicing we can access substrings. It can get optional start and stop indices.

s = ' hello '


s = s[3:8] # no crash if s[3:20]
# 'hello'

2. strip()
Return a copy of the string with the leading and trailing characters removed. The chars argument is
a string specifying the set of characters to be removed. If omitted or None, the chars argument
defaults to removing whitespace.

s = ' hello '.strip()


# 'hello'

3./4. lstrip() and rstrip()


lstrip([chars]) : Return a copy of the string with leading characters removed. rtrip([chars]) :
Return a copy of the string with trailing characters removed.

s = ' hello '.lstrip()


# 'hello '

s = ' hello '.rstrip()


# ' hello'

strip() with character

We can specify character(s) instead of removing the default whitespace.

s = '###hello###'.strip('#')
# 'hello'

Careful: only leading and trailing found matches are removed:

s = ' \n \t hello\n'.strip('\n')
# -> not leading, so the first \n is not removed!
# ' \n \t hello'

s = '\n\n \t hello\n'.strip('\n')
# ' \t hello'
strip() with combination of characters

The chars argument is a string specifying the set of characters to be removed. So all occurrences
of these characters are removed, and not the particular given string.

s = 'www.example.com'.strip('cmow.')
# 'example'

5./6. removeprefix() and removesuffix()


Like seen before, strip, lstrip, and rstrip remove all occurrences of the passed chars string. So if we
just want to remove the given string, we can use remove prefix and removesuffix.

s = 'Arthur: three!'.lstrip('Arthur: ')


# 'ee!'

s = 'Arthur: three!'.removeprefix('Arthur: ')


# 'three!'

s = 'HelloPython'.removesuffix('Python')
# 'Hello'

7. replace()
Return a copy of the string with all occurrences of substring old replaced by new.

s = ' \n \t hello\n'.replace('\n', '')


# ' \t hello'

8. re.sub()
If we want to replace a specific pattern with another character, we can use the re module and use a
regular expression.

import re
s = "string methods in python"
s2 = re.sub("\s+" , "-", s)
# 'string-methods-in-python'

More about regular expression can be learned in this Crash Course.


9. split()
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at
most maxsplit splits are done.

s = 'string methods in python'.split()


# ['string', 'methods', 'in', 'python']

s = 'string methods in python'.split(' ', maxsplit=1)


# ['string', 'methods in python']

10. rsplit()
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at
most maxsplit splits are done, the rightmost ones.

s = 'string methods in python'.rsplit()


# ['string', 'methods', 'in', 'python']

s = 'string methods in python'.rsplit(' ', maxsplit=1)


# ['string methods in', 'python']

11. join()
Return a string which is the concatenation of the strings in iterable.

list_of_strings = ['string', 'methods', 'in', 'python']


s = ' '.join(list_of_strings)
# 'string methods in python'

12./13./14. upper(), lower(), capitalize()


Return a copy of the string with all the cased characters converted to uppercase, lowercase, or first
character capitalized and the rest lowercased.

s = 'python is awesome!'.upper()
# 'PYTHON IS AWESOME!'

s = 'PYTHON IS AWESOME!'.lower()
# 'python is awesome!'
s = 'python is awesome!'.capitalize()
# 'Python is awesome!'

15./16. islower(), isupper()


Checks if the string consist only of upper or lower characters.

'PYTHON IS AWESOME!'.islower() # False


'python is awesome!'.islower() # True

'PYTHON IS AWESOME!'.isupper() # True


'PYTHON IS awesome!'.isupper() # False

17./18./19. isalpha(), isnumeric(), isalnum()


isalpha() : Return True if all characters in the string are alphabetic and there is at least one
character, False otherwise. isnumeric() : Return True if all characters in the string are numeric
characters, and there is at least one character, False otherwise. isalnum() : Return True if all
characters in the string are alphanumeric and there is at least one character, False otherwise.

s = 'python'
print(s.isalpha(), s.isnumeric(), s.isalnum() )
# True False True

s = '123'print(s.isalpha(), s.isnumeric(), s.isalnum() )


# False True True

s = 'python123'
print(s.isalpha(), s.isnumeric(), s.isalnum() )
# False False True

s = 'python-123'
print(s.isalpha(), s.isnumeric(), s.isalnum() )
# False False False

20. count()
Return the number of non-overlapping occurrences of substring sub in the range [start, end].

n = 'hello world'.count('o')
# 2
21. find()
Return the lowest index in the string where substring sub is found within the slice s[start:end].

s = 'Machine Learning'
idx = s.find('a')
print(idx) # 1
print(s[idx:]) # 'achine Learning'

idx = s.find('a', 2)
print(idx) # 10
print(s[idx:]) # 'arning'

22. rfind()
Return the highest index in the string where substring sub is found, such that sub is contained
within s[start:end].

s = 'Machine Learning'
idx = s.rfind('a')
print(idx) # 10

23./24. startswith() and endswith()


Return True if string starts/ends with the prefix/suffix, otherwise return False.

s = 'Patrick'.startswith('Pat') # case sensitive!


# True

s = 'Patrick'.endswith('k') # case sensitive!


# True

25. partition()
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the
separator, the separator itself, and the part after the separator. If the separator is not found, return
a 3-tuple containing the string itself, followed by two empty strings.

s = 'Python is awesome!'
parts = s.partition('is')
# ('Python ', 'is', ' awesome!')
parts = s.partition('was')
# ('Python is awesome!', '', '')

26./27./28 center(), ljust(), rjust()


center() : Return centered in a string of length width. Padding is done using the specified fillchar
(default is a space). ljust() : Return the string left justified in a string of length width. Padding is
done using the specified fillchar (default is a space). rjust() : Return the string right justified in a
string of length width. Padding is done using the specified fillchar (default is a space).

s = 'Python is awesome!'
s = s.center(30, '-')
# ------Python is awesome!------

s = 'Python is awesome!'
s = s.ljust(30, '-')
# Python is awesome!------------

s = 'Python is awesome!'
s = s.rjust(30, '-')
# ------------Python is awesome!

29. f-Strings
Since Python 3.6, f-strings can be used to format strings. They are more readable, more concise,
and also faster!

num = 1
language = 'Python'
s = f'{language} is the number {num} in programming!'
# 'Python is the number 1 in programming!'

30. swapcase()
Return a copy of the string with uppercase characters converted to lowercase and vice versa.

s = 'HELLO world'
s = s.swapcase()
# 'hello WORLD'
31. zfill()
Return a copy of the string left filled with ‚0‘ digits to make a string of length width. A leading sign
prefix (‚+‘/'-') is handled by inserting the padding after the sign character rather than before.

s = '42'.zfill(5)
# '00042'

s = '-42'.zfill(5)
# '-0042'

More on Strings
More information about Strings in Python can be found in this article: Strings - Advanced Python
05.

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*

Python Problem-Solving Bootcamp

🚀 Solve 42 programming puzzles over the course of 21 days: Link*


* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank

you! 🙏

You might also like