Python basic series-(3) detailed introduction of strings

Goals:
 Recognize character strings
 Subscript
 Slicing
 Common operation methods

1 Understanding strings
Strings are the most commonly used data type in Python. We generally use quotation marks to create strings. Creating a string is easy, just assign a variable to it.
E.g:

a = 'hello world'
b = "abcdefg"
print(type(a))
print(type(b))

1.1 String characteristics

# 一对引号字符串
name1 = 'Tom'
name2 = 'Rose'

# 三引号字符串
name3 = '''Tom'''
name4 = """Rose"""
a = '''i am Tom,
        nice to meet you !'''
print(a)
b = """i am Rose,
        nice to meet you!"""
print(b)
# 三引号形式的字符串支持换行
# 如果创建一个字符串I'm Tom?
c = "I'm Tom"
d = 'I\'m Tom'  # 这里的单引号注意一下!
print(c)
print(d)

1.2 String input and output

# 字符串的输出
print('hello world')
name = 'Tom'
print('我的名字是%s' % name)
print(f'我的名字是{name}')

# 字符串的输入
# 在Python中,使用input()接收用户输入
password = input('请输入您的密码:')
print(f'您输入的密码是{password}')
print(type(password))

2 subscript

The subscript is also called the index, which is the number. For example, train seat number, the role of seat number: quickly find the corresponding seat according to the number.
The same reason: the function of the subscript is to quickly find the corresponding data through the subscript.

str1 = 'abc'
print(str1)
"""
1.数据在程序运行过程中存储在内存
2.如何得到数据a字符,b字符等?即如何使用字符串中的某个特定的数据?
3.这些字符数据从0开始顺序分配一个编号---使用这个编号精确找到某个字符数据
下标或索引或索引值
str1[下标]
"""
print(str1[0])
print(str1[1])
print(str1[2])

"""
输出结果:
abc
a
b
c
"""

3 slices

Slicing refers to the operation of intercepting a part of the operation object. Strings, lists, and tuples all support slice operations.
3.1 Slicing syntax
Sequence [start position subscript: end position subscript: step length]
Note:
1. Start and end subscripts are left closed and right open, that is, they do not include the data corresponding to the end position, and both positive and negative numbers are acceptable.
2. The step length is the selection interval, both positive and negative integers are acceptable, the default step length is 1.
Example 1:

name = "abcdefg"
print(name[2:5:1])  # cde
print(name[2:5])   # cde
print(name[:5])  # abcde
print(name[1:])   # bcdefg

Example 2:

# 序列名[开始下标位置:结束下标位置:步长]
str1 = '012345678'
print(str1[2:5:1])   # 234
print(str1[2:5:2])   # 24
print(str1[2:5])    # 234
print(str1[:5])     # 01234---如果不写开始,默认从0开始
print(str1[2:])     # 2345678---如果不写结束,默认选取到最后
print(str1[:])      # 012345678---如果不写开始和结束,表示选取全部

# 负数测试
print(str1[::-1])   # 876543210---步长为负数,表示倒叙选取
print(str1[-4:-1])  # 567---下标-1表示最后一个数据,一次向前类推

# 终极测试 str1 = '012345678'
print(str1[-4:-1:1])    # 567

print(str1[-4:-1:-1])
# 不能选取出数据:从-4开始到-1结束,选取方向从左到右,而步长-1表示从右向左选取
# ***如果选取方向(下标开始到结束的方向)和步长的方向冲突,则无法选取数据

4 Common operating methods

4.1 Search The
so-called string search method is to find the position or number of occurrences of the substring in the string.
 find()—Check whether a certain substring is contained in the string, if it is, return the index of the starting position of the substring, otherwise return -1.

# 语法:字符串序列.find(子串,开始下标,结束位置下标)
# 注意:开始,结束位置下标可以省略,表示在整个字符串序列中查找
mystr = "hello world and itcast and itheima and Python"
print(mystr.find('and'))   # 12
print(mystr.find('and', 15, 30))  # 23
print(mystr.find('ands'))  # -1

 index()—Check whether a certain substring is contained in this string, and return the index at the beginning of the substring, otherwise report an exception.

# 语法:字符串序列.index(子串,开始位置下标,结束下标位置)
# 注意:开始,结束位置下标可以省略,表示在整个字符串序列中查找
mystr = "hello world and itcast and itheima and Python"
print(mystr.index('and'))  # 12
print(mystr.index('and', 15, 30))  # 23
print(mystr.index('ands'))  # 报错

 rfind()—same function as find(), but the search direction starts from the right
 rindex()—functions the same as index(), but the search direction starts from the right
 count()—returns a certain substring Number of occurrences in the string

# 语法:字符串序列.count(子串,开始位置下标,结束下标位置)
# 注意:开始,结束位置下标可以省略,表示在整个字符串序列中查找

example:

mystr = "hello world and itcast and itheima and Python"
# 1,rfind()
print(mystr.rfind('and'))  # 35
print(mystr.rfind('ands'))  #-1
# 2,rindex()
print(mystr.rindex('and'))  #35
# print(mystr.rindex('ands'))  # 报错
# 3,count()
print(mystr.count('and', 15, 30))  # 1
print(mystr.count('and'))  # 3
print(mystr.count('ands'))  # 0

4.2 Modification The
so-called modification of a character string refers to the modification of the data in the character string in the form of a function.
4.2.1 Common Modifications
 replace()----replace

mystr = "hello world and itcast and itheima and Python"
print(mystr.replace('and', 'he'))
# 结果hello world he itcast he itheima he Python
print(mystr.replace('and', 'he', 10))
# 结果hello world he itcast he itheima he Python
print(mystr)
# 结果hello world and itcast and itheima and Python
语法:字符串序列.replace(旧子串,新子串,替换次数)
注意:替换次数如果超出子串出现次数,则替换次数为该子串出现的次数

Note: According to whether the data can be directly modified, there are two types: variable type and immutable type. When the data of the string type is modified, the original string cannot be changed. It belongs to the type that cannot directly modify the data, that is, the immutable type.

 split()----Split the string according to the specified character
Note: If the split character is a substring of the original string, the substring will be lost after splitting.

mystr = "hello world and itcast and itheima and Python"
print(mystr.split('and'))
# 结果:['hello world ', ' itcast ', ' itheima ', ' Python']
print(mystr.split('and', 2))
# 结果:['hello world ', ' itcast ', ' itheima and Python']
print(mystr.split(' '))
# 结果:['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
print(mystr.split(' ', 2))
# 结果:['hello', 'world', 'and itcast and itheima and Python']

 join()-Combine strings with one character or substring, that is, combine multiple strings into a new string.

# join语法---字符或子串.join(多字符组成的序列)
mylist = ['aa', 'bb', 'cc']
new_str = '...'.join(mylist)
print(new_str)
# 结果:aa...bb...cc

4.2.2 Need to know the modifications

 capitalize()----convert the first character of the string to uppercase
Note: After the capitalize() function is converted, only the first character of the string is uppercase, and all other characters are lowercase.
 title()----convert the first letter of each word of the string to uppercase.
 lower()----change uppercase in a string to lowercase
 upper()---- change lowercase in a string to uppercase
Example:

mystr = "hello world and itcast and itheima and Python"
# 1,解释:将第一个字符转换成大写
#  结果:Hello world and itcast and itheima and python
print(mystr.capitalize())

# 2,解释:将每个单词首字母转成大写
#  结果:Hello World And Itcast And Itheima And Python
print(mystr.title())

# 3,解释:将字符串中的大写转换为小写
#  结果:hello world and itcast and itheima and python
print(mystr.lower())

# 4,解释:将字符串中的小写转大写
#  结果:HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON
print(mystr.upper())

L Remove empty functions
Strip () white space on both sides of the string ---- remove
the lstrip () ---- remove white space left string
The rstrip () to delete the right string ---- whitespace
example:
Insert picture description here
l alignment Function
Ijust()----returns a new string with the original string justified to the left and filled to the corresponding length with the specified characters (default spaces).

# 语法:字符串序列.ljust(长度,填充个字符)

rjust()----returns a new string with the original string right-justified and filled to the corresponding length with the specified characters (default spaces). The syntax is the same as ljust().
center()----returns a new string with the original string aligned in the center and filled to the corresponding length with the specified characters (default spaces). The syntax is the same as ljust().
example:
Insert picture description here

4.3 Judgment The
so-called judgment is to judge true or false, and the returned result is Boolean data: True or False
 startswith()—check whether the string starts with the specified substring, if yes, return True, otherwise return False. If you set the start and end position subscripts, check within the specified range.
Syntax:
string sequence. satrtswith (substring, start position index, end position index)
example:

mystr = "hello world and itcast and itheima and Python"
# 1,startswith():判断字符串是否以某个子串开头
print(mystr.startswith('hello'))
print(mystr.startswith('hel'))
print(mystr.startswith('hels'))

# 2,endswith():判断字符串是否以某个子串结尾
print(mystr.endswith('Python'))
print(mystr.endswith('Pythons'))

 isalpha()—If the string has at least one character and all characters are letters, it returns True, and vice versa.

mystr1 = 'hello'
mystr2 = 'hello12345'
print(mystr1.isalpha())
print(mystr2.isalpha())

 isdigit()—If the string contains only digits, it returns True, and vice versa.
 isalnum()—returns True if the string has at least one character and all characters are letters or numbers, and vice versa.

mystr1 = 'aaa12345'
mystr2 = '12345'
print(mystr1.isdigit())
print(mystr2.isdigit())

print(mystr1.isalnum())
print(mystr2.isalnum())

 isspace()----If the string contains only blanks, it returns True, and vice versa.

mystr3 = '1 2 3 4 5'
mystr4 = '     '
print(mystr3.isspace())
print(mystr4.isspace())

There are so many introductions about strings, and friends who like it are recommended to collect them!

Guess you like

Origin blog.csdn.net/qq_46009608/article/details/109248941