欢迎关注微信公众号(医学生物信息学),医学生的生信笔记,记录学习过程。
单引号和双引号
print('I told my friend, "Python is my favorite language!"')
print("The language 'Python' is named after Monty Python, not the snake.")
print("One of Python's strengths is its diverse and supportive community.")
多行字符串
info='''地址:北京市
收件人:LLA
手机号:12300000000
'''
info2="""地址:北京市
收件人:LLA
手机号:12300000000
"""
print(info)
print('------------------')
print(info2)
转义字符
print("Python")
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")
print("Languages:\n\tPython\n\tC\n\tJavaScript")
print('北京')
print('欢迎你')
print('------------')
print('北京\n欢迎你') # 遇到\n即换行,可以连续换多行
print('北\n京\n欢\n迎\n你')
print('-----------')
print('北京北京\t欢迎你')
print('hello\toooo') # hello是5个字符 ,一个制表位是8个字符 8-5=3
print('hellooooo')
print('老师说:\'好好学习,天天向上\'')
print('老师说:\"好好学习,天天向上\"')
原字符,使转义字符失效的符号r或R:
print(r'北\n京\n欢\n迎\n你')
print(R'北\n京\n欢\n迎\n你')
字符串的索引和切片
s='HELLOWORLD'
print(s[0],s[-10]) # 序号0和序号-10表示的是同一个字符
print('北京欢迎你'[4]) # 获取字符串中索引为4
print('北京欢迎你'[-1])
print('---------------------')
print(s[2:7]) # 从2开始到7结束不包含7 正向递增
print(s[-8:-3]) # 反向递减
print(s[:5]) # 默认从 0开始
print(s[5:]) # 默认是切到字符串的结尾
连接、重复字符串
x='2022年'
y='北京冬奥会'
print(x+y) # 连接两个字符
print(x*10) # 对x这个字符串的内容复制10次
print(10*x)
A字符串是否包含于B字符串
x in s
:如果x是s的子串,结果为True
,否则结果为False
。
y='北京冬奥会'
print('北京' in y) # True
print('上海' in y ) # False
修改字符串大小写
首字母大写
name = "ada lovelace"
print(name.title())
全大写
name = "Ada Lovelace"
print(name.upper())
全小写
name = "Ada Lovelace"
print(name.lower())
在字符串中使用变量
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}!")
删除字符串中空白
删除字符串右端空白
可使用rstrip()
函数。
favorite_language = 'python '
favorite_language
favorite_language.rstrip()
删除字符串左端空白
可使用lstrip()
函数。
favorite_language = ' python'
favorite_language.lstrip()
删除字符串两端空白
可使用strip()
函数。
favorite_language = ' python '
favorite_language.strip()
删除前缀
nostarch_url = 'https://nostarch.com'
print(nostarch_url)
print(nostarch_url.removeprefix('https://'))
参考资料
[1] https://www.bilibili.com/video/BV1wD4y1o7AS/?p=7&share_source=copy_web&vd_source=d40f0854606900163a564a59cfa3027c
[2] 零基础Python学习笔记 明日科技编著
[3] Python编程从入门到实践(第3版)