[Introduction to Python] Thorough explanation of the character string type used in Python!

Reference site: [Introduction to Python] Thorough explanation of the character string type used in Python!

[Introduction to Python] Thorough explanation of the character string type used in Python!

Python handles various data types. Of these, the string type is most often used. Compared to other languages, Python is easier to work with strings and has many useful methods.

This time, I will explain the basics of string types in Python.

Representation of strings

To represent a string in Python, enclose it in either single quotation marks (') or double quotation marks ("). It doesn't matter which one you use, but be sure to unify it.'And" It becomes confusing when used in a mixed manner.

Both are the same, but let's unify to either one

print('Hello, World')
print("Hello, World")

Execution result

Hello, World Hello, World

String concatenation and iteration

A character string or a variable that stores a character string can be concatenated with the "+" operator and repeated with the "*" operator.

str1 = 'Python'
str2 = 'Programming'

print(str1 + ' ' + str2)
print(str1 * 3)

Execution result

Python Programming PythonPythonPython

Slice operation

Python strings can be indexed, and the index can be used to retrieve one of the strings. Note that the index starts at 0 instead of 1. If a negative number is specified, the numbers will be counted in order from the right. Also note that negative indexes start with -1 instead of 0.

str1 = 'Python'

print(str1[3])   #Extract the third character
print(str1[-3])  #Extract the third character from the right

Execution result

h h

Python also supports slicing operations. By using slices, you can extract only the character strings in the specified range. The method of slicing is as follows.

String [Index to start slicing: Index to end slicing]

Note that the "index to start slicing" character is included in the slice result, but not the "index to end slicing" character. In other words, it is fetched up to the "index that ends the slice – 1".

str1 = 'Python'

print(str1[2:4])  #Take out from 2nd to 3rd
print(str1[1:5])  #Take out from 1st to 4th

Execution result

th ytho

In addition, the index that starts slicing and the index that ends can be omitted. If the index that starts is omitted, 0 is specified, and if the index that ends is omitted, the size of the character string (= up to the last character) Will be specified.

str1 = 'Python'

print(str1[:5])   #Take out from 0th to 4th
print(str1[1:])   #Take out from first to last

Execution result

Pytho ython

Main string methods

format

format is used to specify the format of a string or variable and embed it in another string. For example, it is used when printing an arbitrary character string and variable together.

'Arbitrary string{0}{1}…'.format(Variable 1,Variable 2 ....)

In any string, put {} where you want to embed the string or variable. Then, the argument of the format method is embedded in the {}. If you want to embed multiple strings or variables, put {} in the string along with the subscripts such as {0}, {1} and pass it to format as multiple arguments.

a = 1
b = 2

print('{0} + {1} = {2}'.format(a, b, a + b))

Execution result

1 + 2 = 3

index

index checks if a string contains the specified character or string, and if so, returns the first index in which the character or string was found.

String.index(探したいString[Starting position,End position])

You can use slices to specify where to start and where to end the search. Both can be omitted, and if both are omitted, the entire character string will be searched.

str1 = 'python programming'

print(str1.index('th'[1:10]))

Execution result

3

split

split is a method that splits a string by any string. The divided character string becomes a list type.

list= 'String'.split(区切りString,Maximum number of divisions)

The maximum number of divisions can be omitted, and if omitted, the character string will be divided as much as possible.

str1 = 'python, programming, start'

print(str1.split(','))

Execution result

[‘python’, ‘ programming’, ‘ start’]

Recommended Posts

[Introduction to Python] Thorough explanation of the character string type used in Python!
[Introduction to Python] How to split a character string with the split function
[Python] PCA scratch in the example of "Introduction to multivariate analysis"
[Introduction to Python] How to output a character string in a Print statement
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
How to quickly count the frequency of appearance of characters from a character string in Python?
I want to batch convert the result of "string" .split () in Python
[Introduction to Python] How to write a character string with the format function
Used from the introduction of Node.js in WSL environment
How to get the number of digits in Python
Store Japanese (multibyte character string) in sqlite3 of python
[Python] How to expand variables in a character string
[Introduction to Python] Basic usage of the library matplotlib
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
Explanation of NoReverseMatch error in "python django super introduction"
I tried to summarize the string operations of Python
I used Python to find out about the role choices of the 51 "Yachts" in the world.
Find out the apparent width of a string in python
Practice! !! Introduction to Python (Type Hints)
In the python command python points to python3.8
6 ways to string objects in Python
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
Supplement to the explanation of vscode
Specify the encoding of the unicode string in the Python 2.x print statement
How to know the internal structure of an object in Python
[Cloudian # 9] Try to display the metadata of the object in Python (boto3)
How to check the memory size of a variable in Python
[Introduction to Python] I compared the naming conventions of C # and Python.
Output the contents of ~ .xlsx in the folder to HTML with Python
Timezone specification when converting a string to datetime type in python
I wrote the code to write the code of Brainf * ck in python
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
[Introduction to Udemy Python3 + Application] 12. Indexing and slicing of character strings
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
What to do when the value type is ambiguous in Python?
Conversion of string <-> date (date, datetime) in Python
[Introduction to Udemy Python3 + Application] 28. Collective type
[Introduction to Python] How to use class in Python?
Check the behavior of destructor in Python
General Theory of Relativity in Python: Introduction
[Introduction to Udemy Python3 + Application] 13. Character method
[Introduction to Udemy Python3 + Application] 21. Tuple type
The result of installing python in Anaconda
[Pandas] Expand the character string to DataFrame
[Introduction to Udemy Python3 + Application] 11. Character strings
The basics of running NoxPlayer in Python
Basic grammar of Python3 system (character string)
In search of the fastest FizzBuzz in Python
[Python] Get the character code of the file
Python basic course (4 numeric type / character string type)
[Introduction to Udemy Python3 + Application] 16. List type
[PowerShell] Get the reading of the character string
Introduction to Vectors: Linear Algebra in Python <1>
Introduction to Effectiveness Verification Chapter 1 in Python
[Introduction to Data Scientists] Basics of Python ♬
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
Explanation and implementation of the XMPP protocol used in Slack, HipChat, and IRC
Good book "Introduction to Python3", N selection (N = 1) where the explanation has failed.
[Python] How to change character string (str) data to date (strptime of datetime)
[Introduction to Python] How to sort the contents of a list efficiently with list sort