Day2-------string

Table of contents

1. Basic knowledge

1. Indicates: single quotation mark double quotation mark triple quotation mark

2. Subscript

3. Slice variable [start:end:step]

4. String search related operations

4. String replacement, cutting, splicing

5. Other methods

Two, training

Topic 1 [Strengthen training]

Question stem

training target

training tips

Reference plan

Steps

reference answer

Topic 2 [Strengthen training]

Question stem

training target

training tips

Reference plan

Steps

reference answer

Topic 3 [Strengthen training]

Question stem

training target

training tips

Reference plan

Steps

reference answer

Topic 4 [Strengthen training]

Question stem

training target

training tips

Reference plan

Steps

reference answer

Topic 5 [Strengthen training]

Question stem

training target

training tips

Reference plan

Steps

reference answer


1. Basic knowledge

1. Indicates: single quotation mark double quotation mark triple quotation mark

2. Subscript

my_str='hello'
# 变量[下标]
print(my_str[0])
# len() 字符串长度
print(len(my_str))
# 获取最后一个元素
print(my_str[-1])
print(my_str[len(my_str)-1])

3. Slice variable [start:end:step]

# 获得到新字符串
# 不包含end对应下标
# step默认为1,可以不写
print(my_str[2:4:1])
# end不写,表示len(),可以取到最后一个元素
print(my_str[2:])
# start不写,表示0
print(my_str[:3])
# :不能一个都不写
print(my_str[:])
# 步长可以是负数
print(my_str[3:1:-1])
# 逆置
print(my_str[::-1])
# 其他
print(my_str[-4:-1])
print(my_str[::2])

4. String search related operations

my_str='hello world itcast and itcastcop'

# find() 查找是否存在某个字符串  返回下标 没找到返回-1
# find(要查找的内容,开始位置,结束位置)
print(my_str.find('hello'))
print(my_str.find('hello',3)) # 没找到返回-1
print(my_str.find('itcast'))
print(my_str.find('itcast',15))
# rfind() 从右边开始查找 返回正下标
print(my_str.rfind('itcast'))

# index() 查找是否存在某个字符串  返回下标 没找到报错
print(my_str.index('hello'))
# print(my_str.index('hello',5)) 没有找到报错

# rindex() 从右边开始查找

# count() 统计出现次数
print(my_str.count('aaa'))
print(my_str.count('hello'))
print(my_str.count('itcast'))
print(my_str.count('itcast',20))

4. String replacement, cutting, splicing

# 字符串替换
# replace(old_str,new_str,count)
# count 替换次数 默认全部替换
# 返回: 得到一个新字符串,不改变原来字符串
print(my_str.replace('itcast','itheima'))
print(my_str.replace('itcast','itheima',1))

# 字符串切割
# split(sub_str,count)  将原字符串按照指定的字符串切割,count表示切割次数
# sub_str 默认空格
# 返回一个列表 不包含切割的字符
# partition() 包含切割的字符
print(my_str.partition('itcast'))
print(my_str.split())
print(my_str.split('itcast'))
print(my_str.split('itcast',1))
# rsplit() 从右边切割

# 字符串拼接
# join(可迭代对象) 不改变原字符串
# 可迭代对象 字符串,列表(字符串类型)
# 将字符串添加到可迭代对象的两个元素之间
print('**'.join('hello'))
my_list=['hello','ly','adfs']
print('*_*'.join(my_list))

5. Other methods

my_str.capitalize() # 字符串首字符大写
my_str.title() # 字符串所有首字符大写
my_str.upper() # 字符串全部大写
my_str.lower() # 字符串全部小写
my_str.islower() # 字符串是否小写
my_str.startswith('hello') # 是否以..开头
my_str.endswith('aa')   # 是否以..结尾
my_str.center(30)  #在某段长度居中
my_str.ljust(30)    #左对齐
my_str.rjust(30)    #右对齐
my_str.lstrip()     #去除左边空格
my_str.rstrip()     #去右边空格
my_str.strip()      #去除两边空格
my_str.isspace() #判断是否有空格
my_str.isalnum() #是否字母或数字
my_str.isdigit() #否纯数字

Two, training

Topic 1 [Strengthen training]

Question stem

If we need to use variables to save the following strings, how should we write the code

Lu Xun said: "I never said that"

training target

Let students know the way that contains string nesting

training tips

In python, there are two forms of expression that can be defined as string types. Which two ways are they and can they be used in combination?

Reference plan

Strings can be defined using both " " and ' '

Steps

  1. Want to include in a string 双引号"", the string can be defined using single quotes
  2. If you want to include it in a string 单引号'', the string can be defined with double quotes

reference answer

# 在python中,''可以嵌套在""中,用以表示字符串中的字符串
words = "鲁迅说:'我没有说过这句话'"
print(words)

# 还可以使用三引号
words = """鲁迅说:'我没有说过这句话'"""
print(words)

Topic 2 [Strengthen training]

Question stem

Make a simple user information management system: Prompt the user to enter name, age and hobbies in turn, and after the input is completed, display the data entered by the user at one time

training target

String declaration String input String output

training tips

  1. In python, declare a variable of type string by "" or ''
  2. Get data from keyboard using input() function
  3. Output string type through %s formatting operator

Reference plan

  1. Enter string data through the input function
  2. Use the string type to save the entered data
  3. Use %s to format and output saved data

Steps

  1. Enter string data through the input function
  2. Use the string type to save the entered data
  3. Use %s to format and output saved data

reference answer

# 录入数据,并保存在变量中
name = input("请输入姓名:")
age = input("请输入年龄:")
hobby = input("请输入您的爱好:")

# 格式化输出数据
print("您的姓名是%s, 您的年龄是%s, 您的爱好是%s" % (name, age, hobby))
# 使用 f-string
print(f"您的姓名是{name}, 您的年龄是{age}, 您的爱好是{hobby}")

Topic 3 [Strengthen training]

Question stem

The existing string is as follows, please use slice to extract ceg words = "abcdefghi"

training target

Slicing of strings using

training tips

1. Slicing syntax: [start:end:step] 2. The selected interval starts from the "start" bit and ends at the bit before the "end" bit (excluding the end bit itself), 3. step size Indicates the selection interval. The default step size is a positive value, that is, it is selected from left to right. If the step size is negative, it is selected from right to left

Reference plan

1. Use slices for interception, the start position is -7, the end position is -1 2. Reverse selection, the step size is 2

Steps

  1. The starting position is -7, the ending position is -1, and the step size is 2

reference answer

a = "abcdefghi"

b = a[-7:-1:2]
print(b)

Topic 4 [Strengthen training]

Question stem

James has a project about crawlers. He needs to search for the keyword python in a string. Currently, he uses the index() function to search. Although the search can be realized, an error will always be reported when the keyword is not found. , why an error is reported, and how to optimize it?

training target

  1. Understand the difference between the find function and the index function

training tips

  1. The find function returns the index value if found, and -1 if not found
  2. The index function returns the index value if it is found, and reports an error if it cannot be found

Reference plan

  1. Replace the index by using the find function

Steps

  1. Replace the index by using the find function

reference answer

只需要使用find函数替换掉index函数即可,在功能上, find函数index函数完全一致,不同的是index函数在没有查找到关键字的情况下会报ValueError的异常,因此在一般开发环境下通常都会使用find函数

Topic 5 [Strengthen training]

Question stem

1. Determine whether the word great is in the string words, if it is, add an s after each great, if not, output that great is not in the string 2, change each word in the entire string into lowercase, And make the first letter of each word uppercase 3, remove the blanks at the beginning and the end, and output the processed string

words = " great craTes Create great craters, But great craters Create great craters "

training target

  1. String operations

training tips

  1. String related operations to solve the above problems
  2. Use the judgment statement to judge the condition of the statement

Reference plan

  1. Use in to determine whether a substring is in the parent string
  2. Use the replace function to replace a substring
  3. Convert a string to lowercase using the lower function
  4. Use the title function to capitalize the first letter of a word
  5. Use the strip function to remove whitespace at the beginning and end of a string

Steps

  1. Use in to determine whether a substring is in the parent string
  2. Use the replace function to replace a substring
  3. Convert a string to lowercase using the lower function
  4. Use the title function to capitalize the first letter of a word
  5. Use the strip function to remove whitespace at the beginning and end of a string

reference answer

words = " great craTes Create great craters, But great craters Create great craters "

# 判断单词great是否在这个字符串中
if 'great' in words:
	# 将每一个great替换成greats
    words = words.replace("great", "greats")

    # 将单词变成小写
    words = words.lower()

    # 将每一个单词的首字母都大写
    words = words.title()

    # 去除首尾的空白
    words = words.strip()

    # 最后进行输出
    print(words)

else:
    print("great不在该字符串中")

Guess you like

Origin blog.csdn.net/m0_46493223/article/details/126052386