Basic grammar of Python3 system (character string)

Overview

You will study the basic grammar of Python 3 by referring to "Introduction to Python 3" by O'Reilly Japan. I hope it will be helpful for those who want to study Python in the same way.

About Python strings

Since the string is immutable (the value cannot be changed later), the string cannot be rewritten. For example, when changing the first character of ABC to G, an error will occur if the following method is tried.

>>> target = 'ABC'
>>> target[0] = 'G'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

If you want to rewrite it, use a function etc. to get the operation result as a new character string.

Creation / extraction of character strings

Creating a string

>>> #When using single quotes
>>> 'sample'
'sample'

>>> #When using double quotes
>>> "sample"
'sample'

>>> #Single quote(Three)
>>> '''sample'''
'sample'

>>> #Double quote(Three)
>>> """sample"""
'sample'

>>> #Empty string
>>> ''
''

Character concatenation

>>> #Concatenation of literal strings
>>> 'ABC' + 'DEF'
'ABCDEF'

>>> #In the case of literal strings, you can concatenate them just by arranging them.
>>> 'ABC' 'DEF'
'ABCDEF'

>>> #Concatenation of string variables
>>> target1 = 'ABC'
>>> target2 = 'DEF'
>>> target1 + target2
'ABCDEF'

>>> #In the case of string variables, just arranging them will result in an error
>>> target1 = 'ABC'
>>> target2 = 'DEF'
>>> target1 target2
  File "<stdin>", line 1
    target1 target2
                  ^
SyntaxError: invalid syntax

Repeat string

>>> 'pyon ' * 5
'pyon pyon pyon pyon pyon '

Extract a specific character from a string

>>> target = 'ABC'
>>> target[0]
'A'
>>> target[1]
'B'
>>> target[2]
'C'

slice

You can use slices to extract substrings from a string.

# [start:end:step]
#   start :Start offset
#   end   :Tail offset
#   step  :Step (every character)

>>> target = 'ABCDEFGHIJKLMN'

>>> #Get the entire string
>>> target[:]
'ABCDEFGHIJKLMN'

>>> #From offset 5 to the end
>>> target[5:]
'FGHIJKLMN'

>>> #Offset 2 to 5
>>> target[2:5]
'CDE'

>>> #Last 3 letters
>>> target[-3:]
'LMN'

>>> #Offset 0 to 10 every 2 steps
>>> target[0:10:2]
'ACEGI'
>>> #It can be omitted like this
>>> target[:10:2]
'ACEGI'

Operation by function

Type conversion by str ()

>>> str(123)
'123'
>>> str(True)
'True'

Replace with replace ()

>>> target = 'ABC'
>>> target.replace('A','G')
'GBC'

Getting the length with len ()

>>> target = 'ABCDE'
>>> len(target)
5

Split by split ()

>>> #Specify a comma for the separator
>>> target = 'AB,C,DE,F'
>>> target.split(',')
['AB', 'C', 'DE', 'F']

>>> #If no separator is specified, whitespace characters (newlines, spaces, tabs) are treated as separators.
>>> target = 'A B C DE F'
>>> target.split()
['A', 'B', 'C', 'DE', 'F']

Join with join ()

The join () function is the inverse of the split () function

>>> #Specify the delimiter, then specify the list
>>> str_list = ['AB', 'C', 'DE', 'F']
>>> target = ','.join(str_list)
>>> print(target)
AB,C,DE,F

First character judgment by startswith ()

>>> target = 'ABCDEFGHIJKLMN'
>>> target.startswith('ABC')
True
>>> target.startswith('BCD')
False

First character judgment by endswith ()

>>> target = 'ABCDEFGHIJKLMN'
>>> target.endswith('LMN')
True
>>> target.endswith('KLM')
False

Get offset with find ()

>>> #If found
>>> target = 'ABCDEFGHIJKLMN'
>>> target.find('D')
3
>>> target.find('DE')
3
>>> #If not found-1 is returned
>>> target.find('DG')
-1
>>> target.find('T')
-1

Counting the number of cases by count ()

>>> target = 'AABBBCAAABCCCCCC'
>>> target.count('A')
5
>>> target.count('B')
4
>>> target.count('C')
7
>>> target.count('AA')
2
>>> target.count('D')
0

Change uppercase and lowercase

Change only the first letter to uppercase with capitalize ()

>>> target = 'thank you for coming.'
>>> target.capitalize()
'Thank you for coming.'

Change all words to title case with title ()

>>> target = 'thank you for coming.'
>>> target.title()
'Thank You For Coming.'

Change all characters to uppercase with upper ()

>>> target = 'thank you for coming.'
>>> target.upper()
'THANK YOU FOR COMING.'

Change all characters to lowercase with lower ()

>>> target = 'THANK YOU FOR COMING.'
>>> target.lower()
'thank you for coming.'

Reverse case with swapcase ()

>>> target = 'AbcdEFg'
>>> target.swapcase()
'aBCDefG'

Character arrangement

Centered with center ()

>>> #Centered in space 40
>>> target = 'thank you for coming.'
>>> target.center(40)
'         thank you for coming.          '

Place at the left end with ljust ()

>>> #Leftmost arrangement in space 40
>>> target = 'thank you for coming.'
>>> target.ljust(40)
'thank you for coming.                   '

Place at the right end with rjust ()

>>> target = 'thank you for coming.'
>>> target.rjust(40)
'                   thank you for coming.'

If you want to know other string functions

Standard documentation for string functions http://bit.ly/py-docs-strings

Recommended Posts

Basic grammar of Python3 system (character string)
Basic grammar of Python3 system (dictionary)
Basic grammar of Python3 system (included notation)
Python3 basic grammar
Basic grammar of Python3 series (list, tuple)
Python basic course (4 numeric type / character string type)
Basic grammar of Python3 system (how to use functions, closures, lambda functions)
Python basic grammar / algorithm
Python basic grammar (miscellaneous)
Python basic grammar note (4)
Python basic grammar note (3)
Basic knowledge of Python
Python basic grammar memo
Calculation of match rate of character string breaks [python]
Basic Python 3 grammar (some Python iterations)
Store Japanese (multibyte character string) in sqlite3 of python
Python installation and basic grammar
Python basic grammar (miscellaneous) Memo (3)
What you want to memorize with the basic "string manipulation" grammar of python
Python basic grammar (miscellaneous) Memo (2)
Basic Python grammar for beginners
Basic usage of Python f-string
I learned Python basic grammar
Python f character (formatted string)
Python basic grammar (miscellaneous) Memo (4)
Python (Python 3.7.7) installation and basic grammar
I wrote the basic grammar of Python with Jupyter Lab
Java and Python basic grammar comparison
Basic study of OpenCV with Python
Python string
Conversion of string <-> date (date, datetime) in Python
(Java, JavaScript, Python) Comparison of string processing
Python UTC ⇔ JST, character string (UTC) ⇒ JST conversion memo
python string comparison / use'list'and'in' instead of'==' and'or'
[Python] How to invert a character string
[Python beginner memo] Python character string, path operation
[Basic grammar] Differences between Ruby / Python / PHP
[Python] I personally summarized the basic grammar.
Python Basic Course (at the end of 15)
[Python] Get the character code of the file
Memo of troubles about coexistence of Python 2/3 system
[PowerShell] Get the reading of the character string
Status of each Python processing system in 2020
A memorandum of python string deletion process
Comparing the basic grammar of Python and Go in an easy-to-understand manner
[Python] How to change character string (str) data to date (strptime of datetime)
[Introduction to Python] Thorough explanation of the character string type used in Python!
Python: String concatenation
Introduction of Python
RF Python Basic_01
python string slice
python grammar check
Basic operation list of Python3 list, tuple, dictionary, set
Divides the character string by the specified number of characters. In Ruby and Python.
[Python] [chardet] Automatic detection of character code of file
python character code
Character range / character string range
Basic Python writing
Character encoding when using csv module of python 2.7.3
Basics of Python ①
This is the only basic review of Python ~ 1 ~