I tried to summarize the string operations of Python

Introduction

I was coding in Python and there was a built-in method that I could use when manipulating strings, so I summarized it as my own memorandum. I don't know how to divide the system because it is organized by individual feeling.

Plastic surgery system

format method

The value in the character string can be described later using index. When used in combination with variables, it makes it easier to edit strings

python


print("This test is {0} for {1}.".format("easy", "you"))
# This test is easy for you.

When using variables


hoge = "easy"
fuga = "you"
print("This test is {0} for {1}.".format(hoge, fuga)) 
# This test is easy for you.

join method

Add the previous value of the method between the arguments Cannot be added after the point starting with the argument and the last character of the argument

python


upper_hoge = "ABC"
lower_hoge = "abc"
print(lower_hoge.join(upper_hoge)) # AabcBabcC

replace method

Replace characters in a string The first argument is the character before replacement The second argument is the replaced character If you give a third argument, you can specify the number of characters to replace.

By setting a blank in the second argument, the target character can be deleted.

hoge = "ababab"
print(hoge.replace('a', 'A'))  # AbAbAb
print(hoge.replace('a', 'A', 1))  # Ababab
print(hoge.replace('a', 'A', 2))  # AbAbab
print(hoge.replace('a', '')) # bbb

strip method

Remove the target string from the beginning and end The strings contained in the arguments are processed regardless of the order if the set matches. Remove the string if there are no arguments

python


hoge = "    A testAtestAtest A     "
#Leading and trailing blanks are removed
print(hoge.strip())  # A testAtestAtest A
#A is not removed because the beginning and end are blank
print(hoge.strip('A'))  #    A testAtestAtest A     

fuga = "A testAtestAtest A"
#Leading and trailing A is removed
print(fuga.strip('A'))  #  testAtestAtest 
#Looking from the beginning and the end, the argument'A','t',' 'The parts that do not correspond to any of
print(fuga.strip(("At "))) # estAtestAtes

lstrip method

Remove the target string from the end The strings contained in the arguments are processed regardless of the order if the set matches. Remove blanks if there are no arguments

python


hoge = "    A testAtestAtest A     "
#Only the leading blank is removed
print(hoge.lstrip())  # A testAtestAtest A
#Since the beginning is blank, nothing is removed because it does not reach the argument A
print(hoge.lstrip('A'))  #     A testAtestAtest A

fuga = "A testAtestAtest A"
#Only the leading A is removed
print(fuga.lstrip('A'))  #  testAtestAtest A
#Looking from the beginning, the argument'A','t',' 'The parts that do not correspond to any of
print(fuga.lstrip(("At ")))  # estAtestAtest A

rstrip method

Remove the target string from the end The strings contained in the arguments are processed regardless of the order if the set matches. Remove blanks if there are no arguments

python


hoge = "    A testAtestAtest A     "
#Only trailing blanks are removed
print(hoge.rstrip())  #     A testAtestAtest A
#Since the end is blank, nothing is removed because it does not reach the argument A.
print(hoge.rstrip('A'))  #     A testAtestAtest A     

fuga = "A testAtestAtest A"
#Only the trailing A is removed
print(fuga.rstrip('A'))  # A testAtestAtest 
#Looking from the end, the argument'A','t',' 'The parts that do not correspond to any of
print(fuga.strip(("At "))) # A testAtestAtes

Search system

find method

Counts from the beginning and returns where the corresponding character exists If the corresponding character does not exist, "-1" is output. It is also possible to pass the search start position and end position as arguments (Note that the index up to the previous index is searched for the value of the end position!)

python


hoge = "test"
print(hoge.find('t'))  # 0
print(hoge.find('a'))  # −1
print(hoge.find('t', 1, 4))  # 3
print(hoge.find('t', 1, 2))  # -1

count method

Print the number of characters in the list

python


#This time output the number of t
hoge = "test"
print(hoge.count('t'))  # 2

Split system

split method

Decompose the string with the argument character and store it in the list The second argument is the number of splits

python


hoge = "a b c d e f g"
print(hoge.split(' '))  # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(hoge.split(' ', 0))  # ['a b c d e f g']
print(hoge.split(' ', 1))  # ['a', 'b c d e f g']
print(hoge.split(' ', 4))  # ['a', 'b', 'c', 'd', 'e f g']

rsplit method

Splits the string like the split method, but splits from the right side when splitting The second argument is the number of splits

python


hoge = "a b c d e f g"
print(hoge.rsplit(' '))  # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(hoge.rsplit(' ', 0))  # ['a b c d e f g']
print(hoge.rsplit(' ', 1))  # ['a b c d e f', 'g']
print(hoge.rsplit(' ', 4))  # ['a b c', 'd', 'e', 'f', 'g']

Discrimination system

startswith method

Method to determine the beginning of a string Returns true if it starts with an argument, false otherwise

python


hoge = "test"
print(hoge.startswith('te'))  # True
print(hoge.startswith('tt'))  # False

endswith method

Method to determine the end of a string Returns true if it ends with an argument, false otherwise

python


hoge = "test"
print(hoge.endswith('st'))  # True
print(hoge.endswith('tt'))  # False

Uppercase / lowercase conversion system

upper method

Convert strings to uppercase

python


lower_hoge = "abc"
print(lower_hoge.upper())  # ABC

lower method

Convert strings to lowercase

python


upper_hoge = "ABC"
print(upper_hoge.lower())  # abc

swapcase method

Swap uppercase and lowercase

python


hoge = "AbcDefG"
print(hoge.swapcase())  # aBCdEFg

capitalize method

Uppercase the first character

python


hoge = "test"
print(hoge.capitalize())  # Test

reference

· Python 3.7.5 documentation https://docs.python.org/ja/3.7/library/stdtypes.html#string-methods

Recommended Posts

I tried to summarize the string operations of Python
I tried to summarize how to use matplotlib of python
I tried to summarize the basic form of GPLVM
I tried to find the entropy of the image with python
[Python] I tried to visualize the follow relationship of Twitter
[Machine learning] I tried to summarize the theory of Adaboost
I tried to summarize Python exception handling
I tried to summarize the umask command
Python3 standard input I tried to summarize
I tried to summarize the graphical modeling.
[Linux] I tried to summarize the command of resource confirmation system
I tried to summarize the frequently used implementation method of pytest-mock
I tried to improve the efficiency of daily work with Python
[Python / DynamoDB / boto3] List of operations I tried
I tried to touch the API of ebay
I tried to correct the keystone of the image
LeetCode I tried to summarize the simple ones
I tried to vectorize the lyrics of Hinatazaka46!
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
I want to batch convert the result of "string" .split () in Python
I tried to get the authentication code of Qiita API with Python.
(Python) I tried to analyze 1 million hands ~ I tried to estimate the number of AA ~
I tried to summarize the logical way of thinking about object orientation.
I tried to verify and analyze the acceleration of Python by Cython
I tried to streamline the standard role of new employees with Python
I tried to summarize SparseMatrix
I tried to get the movie information of TMDb API with Python
I tried to summarize the contents of each package saved by Python pip in one line
I tried to graph the packages installed in Python
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to visualize the spacha information of VTuber
I tried to summarize how to use pandas in python
I tried to erase the negative part of Meros
I tried to solve the problem with Python Vol.1
I tried to classify the voices of voice actors
[Python] I tried to judge the member image of the idol group using Keras
I tried to summarize the settings for various databases of Django (MySQL, PostgreSQL)
I tried to summarize the operations that are likely to be used with numpy-stl
I tried to refactor the code of Python beginner (junior high school student)
I didn't understand the Resize of TensorFlow so I tried to summarize it visually.
I tried to automatically send the literature of the new coronavirus to LINE with Python
I tried to touch Python (installation)
I tried to move the ball
I tried to estimate the interval.
[Horse Racing] I tried to quantify the strength of racehorses
I tried "gamma correction" of the image with Python + OpenCV
I tried to simulate how the infection spreads with Python
[First COTOHA API] I tried to summarize the old story
I tried to get the location information of Odakyu Bus
I tried the accuracy of three Stirling's approximations in python
I tried to find the average of the sequence with TensorFlow
I tried to summarize the code often used in Pandas
I tried to summarize the commands often used in business
I tried to implement the mail sending function in Python
I want to know the features of Python and pip
[Python] I tried collecting data using the API of wikipedia
I tried to enumerate the differences between java and python
I tried to fight the Local Minimum of Goldstein-Price Function
I tried changing the python script from 2.7.11 to 3.6.0 on windows10