“”" python基础学习"“”
打印 hello python world
print(“hello python world”)
1、变量名
message = “hello python world”
print("message = ",message)
message = “hello python crash course world” # 遍历可重复赋值
print("message = ",message)
2、字符串
str1 = ‘This is a string’
print(str1)
str2 = “This is a string”
print(str2)
str3 = ‘I told friend,“Python is my favorite language!”’
print(str3)
str4 = "The language ‘Python’ is named after Monty Python, not the snake. "
print(str4)
str5 = “One of Python’s strengths is its diverse and supportive comunnity.”
print(str5)
2.1 修改字符串的大小写
name = “ada lovelace.”
print(name.title()) # 字符串首字母改为大写
print(name.upper()) # 字符串全部改为大写
print(name.lower()) # 字符串全部改为小写
案例:用“+”实现字符串拼接
写法一: 在print中先组合,后打印
first_name = “ada”
last_name = “lovelace”
full_name = first_name + " " + last_name
print("Hello, " + full_name.title() + “!”)
写法二:在message变量中先组合,在print中打印
message = "Hello, " + full_name.title() + “!”
print(message)
3、使用指标符(\t)或换行符(\n)来增添空白
\t
print(“\tPython”) # 等价于3个空格
\n : 将字符串多行打印
print(“Languages:\nPython\nC\nJavaScript”)
“”"
输出结果:
Languages:
Python
C
JavaScript
“”"
print(“Languages:\n\tPython\n\tC\n\tJavaScript”)
“”"
输出结果:
Languages:
Python
C
JavaScript
“”"
\n\t的用途:用几行代码输出多行输出
3、删除空白 .rstrip()
favorite_language = 'python ’
注意需要将删除空白后的结果重新赋值给变量,否则再次访问变量还是有空白
print(favorite_language)
favorite_language = favorite_language.rstrip()
print(favorite_language.rstrip())
print(favorite_language)
4、使用字符串应避免的语法错误
单引号括起来的字符串中不能有撇好,双引号括起来中的字符串中可以有
str_d = ‘I’am is wang wei’ 错误写法
print(str_d)
str_s = “I’am is wang xiao” # 正确写法
print(str_s)
练习
1、个性化消息: 将 “Hello Eric, would you like to learn some Python today?”
personal_information = “Hello Eric, would you like to learn some Python today?”
print(personal_information)
2、调整名字的大小写:将一个人名储存到一个变量中,再以小写、大写和首字母大写的方式
显示这个人明
first_name = "wang "
last_name = "xiao "
full_name = first_name + " " + last_name
message_small = "Hello, " + " " + full_name.lower() + “!” # 小写
message_big = "Hello, " + " " + full_name.upper() + “!” # 大写
message_shou_big = "Hello, " + " " + full_name.title() + “!” # 首字母大写
print(message_small)
print(message_big)
print(message_shou_big)
3、打印名言:为中华子崛起而读书 —— 周恩来
say_word = ‘周恩来曾经说过,“为中华之崛起而读书!”’
print(say_word)
4、重复名言:要求将姓名存储到变量famous_person中,在创建要显示的信息,存储到message中
打印信息
famous_person = “周恩来”
message = famous_person + “曾经说过,”"为中华之崛起而读书! "
print(message)
5、删除人名中的空白,存储一个人名,在开头和结尾都包含一些空白,然后分别使用lstrip(),rstrip(),strip()函数处理空白,然后将结果打印出来
famous_person = " 周恩来 "
message = “曾经说过,”"为中华之崛起而读书! "
print(famous_person)
print(famous_person.lstrip() + message) # 只能处理头部空白
print(famous_person.rstrip() + message) # 只能处理尾部空白
print(famous_person.strip() + message) # 头部和尾部空白都能处理