Python String methods
Python
82
Male avatar

loveprogramming viết ngày 04/03/2021

https://grokonez.com/python/python-string-methods

Text or String is one of the most common data type that we have to work as a software developer. In this tutorial, we're gonna look at almost Python String methods which are important when working with text.

Create raw String with escape characters

We use r before quotation mark of a string:


>>> print(r'Play with \'escape\' characters\n\t\\\\')
Play with \'escape\' characters\n\t\\\\

Create multi-lines String

When we put string inside three single quotes/ three double quotes, any quote, tab, or newline will be considered part of the string.

For example:


>>> '''We solve problems with 2 kinds of approach:
...
... - 'grok' so thoroughly that the observer becomes a part of the observed.
... - contrasts 'zen', which is a similar supernatural understanding experienced as a single brief flash.
...
... That's the idea our logo is built around.'''
"We solve problems with 2 kinds of approach:\n\n- 'grok' so thoroughly that the observer becomes a part of the observed.\n- contrasts 'zen', which is a similar supernatural understanding experienced as a single brief flash.\n\nThat's the idea our logo is built around."

Or we can test using a .py file with the code below and run it:


print('''We solve problems with 2 kinds of approach:

- 'grok' so thoroughly that the observer becomes a part of the observed.
- contrasts 'zen', which is a similar supernatural understanding experienced as a single brief flash.

That's the idea our logo is built around.''')

Output:


We solve problems with 2 kinds of approach:

- 'grok' so thoroughly that the observer becomes a part of the observed.
- contrasts 'zen', which is a similar supernatural understanding experienced as a single brief flash.

That's the idea our logo is built around.

Get characters by Index and Slide String

We can apply indexes and slides on Python String with the same way as Python List. Just think of a string as a list and each character in the string as an item:


>>> site = 'grokonez'
>>> site[0]
'g'
>>> site[1]
'r'
>>> site[0:4]
'grok'
>>> site[4:]
'onez'

Python Transform String methods

Upper and Lower String

upper() and lower() methods return a new string (not change the original string) with all letters have been converted to uppercase or lowercase:


>>> site = 'grokonez'

>>> site.upper()
'GROKONEZ'
>>> site
'grokonez'

>>> site = site.upper()
>>> site
'GROKONEZ'
>>> site.lower()
'grokonez'

Swap Upper-Lower String

swapcase() returns a new string that converts all uppercase characters to lowercase and all lowercase characters to uppercase characters.

>>> 'grokonez technology'.swapcase()
'GROKONEZ TECHNOLOGY'

>>> 'GROKONEZ technology'.swapcase()
'grokonez TECHNOLOGY'

Capitalize first letter

  • capitalize() converts first letter of a string to uppercase letter and lowercases others:
    
    >>> 'grokonez programming tutorials'.capitalize()
    'Grokonez programming tutorials'

'GROKONEZ TUTORIALS'.capitalize()
'Grokonez tutorials'

  • title() returns a string with first letter of each word capitalized:
    
    'grokonez programming tutorials'.title()
    'Grokonez Programming Tutorials'

'GROKONEZ programming tutorials'.title()
'Grokonez Programming Tutorials'

Python Validate String methods

Uppercase & Lowercase

isupper() and islower() methods return:

  • True if:
  • the string has at least one letter (not number)
  • all the letters are uppercase/lowercase
  • False for other cases

For example:


>>> site = 'Grokonez'
>>> site.isupper()
False
>>> site.islower()
False

>>> site = 'grokonez'
>>> site.islower()
True

>>> numberString = '12345'
>>> numberString.isupper()
False
>>> numberString.islower()
False

>>> flex = 'abc123'
>>> flex.islower()
True

>>> flex = 'ABC123'
>>> flex.isupper()
True

Letters & Numbers

  • isalpha() returns True if the string has only letters (not blank).
    
    >>> 'grokonez'.isalpha()
    True

'jsa2018'.isalpha()
False

'jsa-tech'.isalpha()
False

'jsa Technology'.isalpha()
False

  • isalnum() returns True if the string has only letters and numbers (not blank).
    
    'grokonez2018'.isalnum()
    True

'jsa-2018'.isalnum()
False

'jsa Technology'.isalnum()
False

  • isdecimal() returns True if the string has only numeric characters (not blank).
    
    '2019'.isdecimal()
    True

'2016and2017'.isdecimal()
False

'2017-2018'.isdecimal()
False

Space

isspace() returns True if the string has only spaces, tabs, and newlines (not blank).


'\n \t'.isspace()
True

'1 '.isspace()
False

Title type

istitle() returns True if the string has only words that begin with an uppercase letter followed by only lowercase letters.


'Grokonez Technology'.istitle()
True

'JSA Technology'.istitle()
False

'Jsa technology'.istitle()
False

Start/End with

  • startswith() returns True if the string value begins with the string passed to the method:
    
    'grokonez Technology'.startswith('grokonez')
    True

'grokonez Technology'.startswith('Tech')
False

'grokonez Technology'.startswith('grokee')
False

'grokonez Technology'.startswith('grokonez Technology')
True

  • endswith() returns True if the string value ends with the string passed to the method:
    
    'grokonez Technology'.endswith('logy')
    True

'grokonez Technology'.endswith('biology')
False

'grokonez Technology'.endswith('grokonez Techno')
False

'grokonez Technology'.endswith('grokonez Technology')
True

Python Join and Split String methods

Join strings

We use join() to join a list of string into a single string value. The returned string is the concatenation of each string in the passed-in list.


', '.join(['dog','cat','tiger'])
'dog, cat, tiger'

' '.join(['grokonez','Programming','tutorials'])
'grokonez Programming tutorials'

Split string

split() is called on a string value and returns a list of strings.


'My website is grokonez.com'.split()
['My', 'website', 'is', 'grokonez.com']

By default, the string is split wherever a whitespace characters (space, tab, or newline) is found. We can pass a delimiter string to the split() method to specify the string to split upon.


'My website is grokonez.com'.split('e')
['My w', 'bsit', ' is grokon', 'z.com']

Partition string

partition() gets argument string as a separator, then:

  • splits the string at the first occurrence of separator
  • returns a tuple containing 3 parts: the string before separator, separator, and the part after separator.
    
    'grokonez programming tutorials'.partition(' ')
    ('grokonez', ' ', 'programming tutorials')

'grokonez programming tutorials'.partition('ming ')
('grokonez program', 'ming ', 'tutorials')

Python Justify Text

Right Justified

rjust() returns a right-justified string with given minimum width.


'grokonez'.rjust(10)
'  grokonez'
# 10 = 2 spaces + 8 letters

'grokonez'.rjust(5)
'grokonez'

By default, spaces will be filled on the left. We can specify a fill character with second argument:


'grokonez'.rjust(10,'=')
'==grokonez'

Left Justified

ljust() returns a left-justified string with given minimum width.


'grokonez'.ljust(10)
'grokonez  '
# 10 = 8 letters + 2 spaces

'grokonez'.ljust(5)
'grokonez'

By default, spaces will be filled on the right. We can specify a fill character with second argument:


'grokonez'.ljust(10,'=')
'grokonez=='

Center

center() works like ljust() and rjust(), but centers the text rather than justifying it to the left or right.


'grokonez'.center(10)
' grokonez '

'grokonez'.center(5)
'grokonez'

'grokonez'.center(10,'=')
'=grokonez='

Strip off characters

  • strip() returns a new string without any whitespace characters at the beginning or end:
    
    '    grokonez  '.strip()
    'grokonez'
    
  • lstrip() removes whitespace characters from the left, and rstrip() removes whitespace characters from the right ends:
    
    '    grokonez  '.lstrip()
    'grokonez  '

' grokonez '.rstrip()
' grokonez'

We can pass a string argument to this method to specify the set of characters to be removed:


'TutsTutsgrokonezTutsPythonTuts'.strip('sTut')
'grokonezTutsPython'

'TutsTutsgrokonezTutsPythonTuts'.lstrip('sTut')
'grokonezTutsPythonTuts'

'TutsTutsgrokonezTutsPythonTuts'.rstrip('sTut')
'TutsTutsgrokonezTutsPython'

*Note: The order of the characters in the string passed to strip() does not matter: strip('sTut') will do the same thing as strip('tTus') or strip('Tuts').

Check Substring in String

We can know whether a string is or is not in a parent string using in or not in operators:


'grok' in 'grokonez Technology'
True

'konez' in 'grokonez Technology'
True

'Grok' in 'grokonez Technology'
False

'' in 'grokonez Technology'
True

'gray' not in 'grokonez Technology'
True

'konez' not in 'grokonez Technology'
False

Python String Finding methods

Count Substrings

count() returns the number of substrings inside the given string.


string = 'grokonez is derived from the words grok and konez'
substring = 'grok'
string.count(substring)
2

Find index of Substring

index() & rindex()

  • index() returns the index of first occurrence of the substring (if found) in the string, or throw an exception when the substring is not found.
    
    string = 'grokonez is derived from the words grok and konez'
    substring = 'konez'

string.index(substring)
3

search within string[5:]

string.index(substring, 5)
44

search in string[2:10]='okonez i'

string.index(substring, 2, 10)
3

search within string[2:7]='okone'

string.index(substring, 2, 7)
Traceback (most recent call last):
File "", line 1, in
ValueError: substring not found

  • rindex() returns the index of last occurrence of the substring (if found) in the string, or throw an exception when the substring is not found.
    
    >>> string = 'grokonez is derived from the words grok and konez'
    >>> substring = 'konez'

string.rindex(substring)
44

search in string[:42]='grokonez is derived from the words grok an'

string.rindex(substring, 0, 42)
3

search in string[10:42]='s derived from the words grok an'

string.rindex(substring, 10, 42)
Traceback (most recent call last):
File "", line 1, in
ValueError: substring not found

find() & rfind()

  • Similar to index()/rindex() method, but there is only one difference: find()/rfind() return -1 if not found.
    
    string = 'grokonez is derived from the words grok and konez'
    substring = 'konez'

string.find(substring)
3

search within string[5:]

string.find(substring, 5)
44

search in string[2:10]='okonez i'

string.find(substring, 2, 10)
3

search within string[2:7]='okone'

string.find(substring, 2, 7)
-1

=== rfind() ===

string.rfind(substring)
44

search in string[:42]='grokonez is derived from the words grok an'

string.rfind(substring, 0, 42)
3

search in string[10:42]='s derived from the words grok an'

string.rfind(substring, 10, 42)
-1

Find and Replace

replace() returns the string in which, every substring is replaced with argument string.


string = 'grokonez is derived from the words grok and konez'
string.replace('nez', 'zen')
'grokozen is derived from the words grok and kozen'
Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

Male avatar

loveprogramming

545 bài viết.
97 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 11 tháng trước
1 0
Male avatar
1 0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 9 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 9 tháng trước
1 0
Bài viết liên quan
White
8 7
Description Mình là một thằng thích đọc sách. Nhưng lúc nào cũng bận (lười) nên cũng mấy tháng rồi chưa hoàn thành được quyển sách nào. Mình đa số...
Rice viết hơn 2 năm trước
8 7
White
5 2
Requirement Hôm bữa đọc được bài https://kipalog.com/posts/Hocvacaithienkienthuctucacduancanhanpetproject thấy hay quá. Tính cũng định viết con ap...
Rice viết hơn 2 năm trước
5 2
White
0 0
(Ảnh) (image from internet) Mở bài Chào mừng mọi người đến với bài post tiếp theo của phần “The Python Tutorial” của series “Khám phá Đại Bản D...
BeautyOnCode viết 1 năm trước
0 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
545 bài viết.
97 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!