Files
2025PY/day04/06-字符串的扩展.py
2025-05-22 16:50:44 +08:00

49 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 一.字符串的三种定义方式
# 1.单引号
str_one = 'hello'
print(str_one)
# 2.双引号
str_two = "你好"
print(str_two)
# 3.三引号
# 注意1三引号定义法和多行注释的写法一样同样支持换行操作
# 使用变量接收,就是字符串
# 不使用变量接收,就是多行注释
# """你好,世界"""
# str_three = """你好,
# 世
# 界
# """
# print(str_three) # 同样支持换行操作
# 二.字符串的引号嵌套规则是单引号可以内含双引号,反之一样
# str = "what's your name"
# print(str) # what's your name
# str1 = '你好世界"欢迎"您'
# print(str1) # 你好世界"欢迎"您
# 三.字符串的拼接
# 1.利用+号
name = '张三'
age = 18
gender = ''
print('我的名字是' + name + ',我今年' + str(age) + '岁,我是' + gender + '' )
# 问题:上面的字符串拼接方式如果变量过多,拼接起来比较麻烦,同时无法和数字等其他类型进行拼接
# 2.字符串格式化,利用%占位实现
# 其中的%S
# % 表示:我要占位
# s 表示:%s将变量变成字符串放入占位的地方
# d 表示:%d代表整数占位符
# f 表示:%f代表浮点数占位符(默认保留6位小数)
# 所以,综合起来的意思就是:我先占个位置,等一会有个变量过来,我把它变成字符串放到占位的位置
name = '张三'
age = 18
gender = ''
print('我的名字是%s,我今年%s岁,我是%s' %(name,age,gender))
# 注意多个变量占位,变量要用括号括起来,并按照占位的顺序填入