python训练营Day2打卡

一、字符串的操作

1.字符串拼接 

 1)使用“ +” 运算符 :直接将多个字符串连接起来

str1 = "Hello"
str2 = " World"
result = str1 + str2
print(result)  # 输出: Hello World

2)使用join() 方法 :适用于连接字符串列表,效率较高。

words = ["Hello", "World", "!"]
result = " ".join(words)
print(result)  # 输出: Hello World!

3)计算字符串长度

# 字符串的操作
str1 = "Hello"
str2 = "Python"

# 字符串拼接(中间加空格)
greeting = str1 + " " + str2

# 计算字符串长度
length = len(greeting)

#输出结果
12

4)字符串获取

# 字符串的操作
str1 = "Hello"
str2 = "Python"

# 字符串拼接(中间加空格)
greeting = str1 + " " + str2

# 获取字符串中的字符
first_char = greeting[0]
second_char = greeting[1]
last_char = greeting[-1]  # 使用-1获取最后一个字符

# 使用f-string分三行打印结果
print(f"第一个字符: {first_char}")
print(f"第二个字符: {second_char}")
print(f"最后一个字符是: {last_char}")

#结果
H
e
n

5)变量定义与结果比较

# 定义变量

score_a = 75

score_b = 90

# 比较运算

is_a_higher = score_a > score_b

is_a_lower_or_equal = score_a <= score_b

is_different = score_a != score_b

# 使用f-string打印比较结果

print(f"{score_a} 是否大于 {score_b}: {is_a_higher}")

print(f"{score_a} 是否小于等于 {score_b}: {is_a_lower_or_equal}")

print(f"{score_a} 是否不等于 {score_b}: {is_different}")

#结果

75 是否大于 90: False
75 是否小于等于 90: True
75 是否不等于 90: True

6)字符串切片

通过指定搜索范围来获取字符串子串

s = "Hello World"
print(s[0:5])  # 输出: Hello
print(s[6:])   # 输出: World

注意:从左到右第一个字符从0开始依次递增;从倒数第一个字符以从右往左的顺序从-1开始依次递减 

python训练营Day2打卡_第1张图片

7)字符串查找

方法一:find() 方法

返回子串首次出现的索引,未找到返回 -1 

s = "Hello World"
index = s.find("World")
print(index)  # 输出: 6

方法二:index() 方法

与 find() 类似,但未找到时会抛出 ValueError 异常。 

8)字符串替换

使用 replace() 方法替换字符串中的指定子串

s = "Hello World"
new_s = s.replace("World", "Python")
print(new_s)  # 输出: Hello Python

9)字符串分割 

使用 split() 方法将字符串按指定分隔符分割成列表。

s = "apple,banana,orange"
fruits = s.split(",")
print(fruits)  # 输出: ['apple', 'banana', 'orange']

10)字符串大小写转换 

- upper() 方法 :将字符串转为大写。
- lower() 方法 :将字符串转为小写。
- title() 方法 :将字符串每个单词的首字母转为大写。

s = "hello world"
print(s.upper())  # 输出: HELLO WORLD
print(s.lower())  # 输出: hello world
print(s.title())  # 输出: Hello World 

11)字符串去除空白

先介绍一下python中斜杠/和反斜杠\的含义

Python 等编程语言里,正斜杠 / 用于表示常规的除法运算,运算结果通常为浮点数。

双斜杠 // 表示整除,它会舍去小数部分,只保留整数结果。

反斜杠\表示转义字符,它能把普通字符转变为有特殊意义的字符,或者把有特殊意义的字符转变为普通字符。

 strip() 方法 :去除字符串首尾的空白字符。不删除原有字符串,而生成一个新字符串

# 包含首尾空白的字符串
s = "  \tHello World\n  "
new_s = s.strip()
print(new_s)  # 输出: Hello World

lstrip() 方法:专门用于去除字符串开头(左侧)的空白字符,同样返回一个新的字符串。 

s = "  \tHello World\n  "
new_s = s.lstrip()
print(new_s)  # 输出: Hello World\n  (仅去除了开头的空白) 

rstrip() 方法:用于去除字符串末尾(右侧)的空白字符,返回新字符串。 

s = "  \tHello World\n  "
new_s = s.rstrip()
print(new_s)  # 输出:      Hello World(仅去除了末尾的空白) 

去除字符串中间的空白(自定义方法)

s = "Hello   World"
new_s = ''.join(s.split())
print(new_s)  # 输出: HelloWorld

#说明

在这个例子中, split() 方法会根据空白字符将字符串分割成多个子字符串,然后 join() 方法再将这些子字符串连接起来,中间不添加任何字符,从而达到去除中间空白的效果。 

二、相关习题

习题一:复杂字符串清洗与格式化

你会得到一个包含用户输入信息的字符串,该字符串格式混乱,包含多余的空白字符、换行符和制表符,并且用户姓名、年龄和职业信息混合在一起。你的任务是对这个字符串进行清洗,提取出有用信息,并按照指定格式输出。

input_str = "  \t 姓名:张三  \n  年龄:28  \t 职业:程序员  \n"

要求输出:

姓名: 张三
年龄: 28
职业: 程序员

input_str = "  \t 姓名:张三  \n  年龄:28  \t 职业:程序员  \n"

# 先去除字符串首尾的空白字符
cleaned_str = input_str.strip()

# 按换行符分割字符串
lines = cleaned_str.split('\n')

for line in lines:
    # 去除每行的空白字符
    line = line.strip()
    if line:
        # 按冒号分割获取键值对
        key, value = line.split(':')
        print(f"{key}: {value.strip()}")

 

习题二:字符串替换与拼接

你有一个包含多个占位符的模板字符串,同时有一个字典存储了占位符对应的实际值。你的任务是将模板字符串中的占位符替换为字典中的实际值,并将替换后的字符串拼接成完整的句子输出。

template = "在 {city} 的 {company} 公司,{name} 是一名 {job},工作了 {years} 年。"
info = {
    "city": "北京",
    "company": "ABC",
    "name": "李四",
    "job": "设计师",
    "years": 5
}

要求输出:

在北京的 ABC 公司,李四是一名设计师,工作了 5 年。 

方法一:使用 format()方法
template = "在 {city} 的 {company} 公司,{name} 是一名 {job},工作了 {years} 年。"
info = {
    "city": "北京",
    "company": "ABC",
    "name": "李四",
    "job": "设计师",
    "years": 5
}

# 使用 format 方法进行替换
result = template.format(**info)
print(result)
 

 方法二:使用 f-string(动态构建)
template = "在 {city} 的 {company} 公司,{name} 是一名 {job},工作了 {years} 年。"
info = {
    "city": "北京",
    "company": "ABC",
    "name": "李四",
    "job": "设计师",
    "years": 5
}

# 动态展开字典为变量
locals().update(info)
# 构建 f-string 表达式并执行
result = eval(f'f"""{template}"""')
print(result)

需要注意的是,eval函数存在安全风险,如果模板和数据来自不可信的来源,不建议使用。通常情况下,format()方法是更安全和推荐的选择。 

 @浙大疏锦行

你可能感兴趣的:(python训练营打卡,python)