Python # string type

Learning notes, memorandums

String type

Created as an instance of the str class. There is no distinction between characters and strings.

Basic method

Basic methods of string type

a = ' Hello, World \n'
 b = a.strip () # Remove whitespace before and after
 c = b.lower () # Convert to lowercase
 d = b.upper () # Convert to uppercase
 e = b.swapcase () # Invert case
 f = b.title () # Convert only the first letter of a word to uppercase
 g = b.split ('') # Split into list by specifying delimiter
 h = b.splitlines () # Split into a list separated by line breaks

Creating a character string considering memory efficiency

Be careful when the loop causes multiple additional string operations, such as when you want to read text data from a file and save that data as a str instance.

Bad example
text = ''

with open('test.txt') as f:
    temp = f.readline()
    while temp:
        text += temp
        temp = f.readline()

In this description method, for each loop, one line of memory is allocated, the memory used up to the previous one and the memory newly read are newly allocated, and the old memory used up to the previous one is released. Since the processing is performed, the memory efficiency is very low and the processing speed is also slow.

Correct example
list = []

with open('test.txt') as f:
    temp = f.readline()
    while temp:
        list.append(temp)
        temp = f.readline()

text = ``.join(list)

To avoid compromising memory efficiency, you can save it as a list and combine it later. By using the join method, you can join the contents of the list by specifying the delimiter character.

Search for strings

startswith (): Whether the string starts with the string specified by the argument ʻEndswith () `: Whether the string ends with the string specified by the argument

find (): Get the index of the character string specified by the argument, -1 if not found ʻIndex (): Get the index of the character string specified by the argument, ValueError if not found You can also use the ʻin operator to determine if it is included.

count (): Count the number of times the character string specified by the argument appears.

String replacement

replace (): Replaces the character string specified by the first argument with the character string specified by the second argument, even if there are multiple target character strings, all are replaced.

Regular expressions

+ Represents one or more repetitions, and * represents zero or more repetitions.

Replacement by external variable

By prefixing the string with f or F, the part enclosed by {} becomes a field that is replaced by an external variable or calculation formula.

a = 'World'
b = f'Hello, {a}'
print(b)

c = 10
d = 20
e = F'{c} + {d} = {c+d}'
print(e)

Execution result

Hello, World 10 + 20 = 30

Format specification

The format () method replaces the index or variable in the {} field with an argument.

a = '{0} is {1}'
b = a.format('apple', 'red')
print(b)

c = '{fruits} is {color}'
d = c.format(fruits = 'melon', color = 'green')
print(d)

Execution result

apple is red melon is green

Right-justified, left-justified, center-justified

Align the character string by filling it with the character string specified after :.

a = 'Title'
b = '{:<10}'.format(a)    # 'Title     '
c = '{:>10}'.format(a)    # '     Title'
d = '{:-^10}'.format(a)    # '--Title---'

Recommended Posts

Python2 string type
Python # string type
Python string
Python: String concatenation
Python string format
Python numeric type
Python string format
Python string inversion
Python basic course (4 numeric type / character string type)
Python callable type specification
[Python] Multi-line string assignment
Python string manipulation master
[Python2] Date string-> UnixTime-> Date string
Random string generation (Python)
Python3> documentation string / docstring
Check Python # type identity
Python string processing illustration
[python] Convert date to string
Python indentation and string format
Python
String object methods in Python
[Python] Use a string sequence
Python --Check type of values
Various Python built-in string operations
Python immutable type int memo
Python data type summary memo
[Python 2/3] Parse the format string
About Python string comparison operators
String date manipulation in Python
Image data type conversion [Python]
python> datetime> From date string (ISO format: 2015-12-09 12:40:08) to datetime type
Python f character (formatted string)
String format with Python% operator
[Python] Type Error:'in <string>' requires string as left operand, not list
Function argument type definition in python
[Translation] Python static type, amazing mypy!
Practice! !! Introduction to Python (Type Hints)
Python for super beginners Python # dictionary type 1 for super beginners
[python] week1-3: Number type and operation
Dynamically load json type in python
Type specified in python. Throw exceptions
String replacement with Python regular expression
6 ways to string objects in Python
[Personal memo] Python sequence type / mapping type
Master the type with Python [Python 3.9 compatible]
python string processing map and lambda
Create a random string in Python
Python for super beginners Python # dictionary type 2 for super beginners
Timezone specification when converting a string to datetime type in python
kafka python
Conversion of string <-> date (date, datetime) in Python
[Introduction to Udemy Python3 + Application] 28. Collective type
Python Summary
Built-in python
Python comprehension
Python technique
Studying python
Shell type
Python 2.7 Countdown
Reintroduction to Python Decorators ~ Learn Decorators by Type ~
Python FlowFishMaster