Python 30天:第四天 -- 字符串
<< 第三天 || 第五天 >>
第四天
字符串
文本是字符串数据类型。任何写成文本的数据类型都是字符串。单引号、双引号或三引号下的任何数据都是字符串。有不同的字符串方法和内置函数来处理字符串数据类型。要检查字符串的长度,请使用 len() 方法。
创建一个字符串
letter = 'P' # A string could be a single character or a bunch of texts
print(letter) # P
print(len(letter)) # 1
greeting = 'Hello, World!' # String could be made using a single or double quote,"Hello, World!"
print(greeting) # Hello, World!
print(len(greeting)) # 13
sentence = "I hope you are enjoying 30 days of Python Challenge"
print(sentence)
多行字符串是通过使用三重单引号 (''') 或三重双引号 (""") 创建的。请参见下面的示例。
multiline_string = '''I am a teacher and enjoy teaching.
I didn't find anything as rewarding as empowering people.
That is why I created 30 days of python.'''
print(multiline_string)# Another way of doing the same thing
multiline_string = """I am a teacher and enjoy teaching.
I didn't find anything as rewarding as empowering people.
That is why I created 30 days of python."""
print(multiline_string)
字符串连接
我们可以将字符串连接在一起。合并或连接字符串称为串联。请参见下面的示例:
first_name = 'Asabeneh'
last_name = 'Yetayeh'
space = ' '
full_name = first_name + space + last_name
print(full_name) # Asabeneh Yetayeh
# Checking the length of a string using len() built-in function
print(len(first_name)) # 8
print(len(last_name)) # 7
print(len(first_name) > len(last_name)) # True
print(len(full_name)) # 16
字符串中的转义序列
在 Python 和其他编程语言中,\ 后跟一个字符是转义序列。让我们看看最常见的转义字符:
- \n: 换行
- \t:Tab 表示(8 个空格)
- \\: 反斜杠
- \':单引号 (')
- \": 双引号 (")
现在,让我们通过示例查看上述转义序列的使用。
print('I hope everyone is enjoying the Python Challenge.\nAre you ?') # line break
print('Days\tTopics\tExercises') # adding tab space or 4 spaces
print('Day 1\t3\t5')
print('Day 2\t3\t5')
print('Day 3\t3\t5')
print('Day 4\t3\t5')
print('This is a backslash symbol (\\)') # To write a backslash
print('In every programming language it starts with \"Hello, World!\"') # to write a double quote inside a single quote# output
I hope every one is enjoying the Python Challenge.
Are you ?
Days Topics Exercises
Day 1 5 5
Day 2 6 20
Day 3 5 23
Day 4 1 35
This is a backslash symbol (\)
In every programming language it starts with "Hello, World!"
字符串格式化
旧式字符串格式(%运算符)
在 Python 中有许多格式化字符串的方法。在本节中,我们将介绍其中的一些。“%”运算符用于格式化包含在“元组”(固定大小列表)中的一组变量,以及格式字符串,格式字符串包含普通文本和“参数说明符”,特殊符号如“%s” , "%d", "%f", "%.number of digitsf".
- %s - 字符串(或任何具有字符串表示形式的对象,如数字)
- %d - 整数
- %f - 浮点数
- "%.number of digitsf" - 具有固定精度的浮点数
# Strings only
first_name = 'Asabeneh'
last_name = 'Yetayeh'
language = 'Python'
formated_string = 'I am %s %s. I teach %s' %(first_name, last_name, language)
print(formated_string)# Strings and numbers
radius = 10
pi = 3.14
area = pi * radius ** 2
formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) # 2 refers the 2 significant digits after the pointpython_libraries = ['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']
formated_string = 'The following are python libraries:%s' % (python_libraries)
print(formated_string) # "The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']"
新式字符串格式(str.format)
这种格式是在 Python 版本 3 中引入的。
first_name = 'Asabeneh'
last_name = 'Yetayeh'
language = 'Python'
formated_string = 'I am {} {}. I teach {}'.format(first_name, last_name, language)
print(formated_string)
a = 4
b = 3print('{} + {} = {}'.format(a, b, a + b))
print('{} - {} = {}'.format(a, b, a - b))
print('{} * {} = {}'.format(a, b, a * b))
print('{} / {} = {:.2f}'.format(a, b, a / b)) # limits it to two digits after decimal
print('{} % {} = {}'.format(a, b, a % b))
print('{} // {} = {}'.format(a, b, a // b))
print('{} ** {} = {}'.format(a, b, a ** b))# output
4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1.33
4 % 3 = 1
4 // 3 = 1
4 ** 3 = 64# Strings and numbers
radius = 10
pi = 3.14
area = pi * radius ** 2
formated_string = 'The area of a circle with a radius {} is {:.2f}.'.format(radius, area) # 2 digits after decimal
print(formated_string)
字符串插值/f-Strings(Python 3.6+)
另一种新的字符串格式是字符串插值,f-strings。字符串以 f 开头,我们可以在其对应的位置注入数据。
a = 4
b = 3
print(f'{a} + {b} = {a +b}')
print(f'{a} - {b} = {a - b}')
print(f'{a} * {b} = {a * b}')
print(f'{a} / {b} = {a / b:.2f}')
print(f'{a} % {b} = {a % b}')
print(f'{a} // {b} = {a // b}')
print(f'{a} ** {b} = {a ** b}')
Python字符串作为字符序列
Python 字符串是字符序列,并与其他 Python 有序对象序列(列表和元组)共享它们的基本访问方法。从字符串(以及任何序列中的单个成员)中提取单个字符的最简单方法是将它们解包到相应的变量中。
解包字符
language = 'Python'
a,b,c,d,e,f = language # unpacking sequence characters into variables
print(a) # P
print(b) # y
print(c) # t
print(d) # h
print(e) # o
print(f) # n
按索引访问字符串中的字符
在编程中计数从零开始。因此,字符串的第一个字母索引为零,字符串的最后一个字母是字符串的长度减一。
language = 'Python'
first_letter = language[0]
print(first_letter) # P
second_letter = language[1]
print(second_letter) # y
last_index = len(language) - 1
last_letter = language[last_index]
print(last_letter) # n
如果我们想从右端开始,我们可以使用负索引。-1 是最后一个索引。
language = 'Python'
last_letter = language[-1]
print(last_letter) # n
second_last = language[-2]
print(second_last) # o
切片Python字符串
在 python 中,我们可以将字符串切片为子字符串。
language = 'Python'
first_three = language[0:3] # starts at zero index and up to 3 but not include 3
print(first_three) #Pyt
last_three = language[3:6]
print(last_three) # hon
# Another way
last_three = language[-3:]
print(last_three) # hon
last_three = language[3:]
print(last_three) # hon
反转字符串
我们可以很容易地在 python 中反转字符串。
greeting = 'Hello, World!'
print(greeting[::-1]) # !dlroW ,olleH
切片时跳过字符
通过将 step 参数传递给 slice 方法,可以在切片时跳过字符。
language = 'Python'
pto = language[0:6:2] #
print(pto) # Pto
字符串方法
有许多字符串方法允许我们格式化字符串。请参阅以下示例中的一些字符串方法:
- capitalize():将字符串的第一个字符转换为大写字母
challenge = 'thirty days of python' print(challenge.capitalize()) # 'Thirty days of python'
- count():返回子字符串在字符串中出现的次数,count(substring, start=.., end=..)。start 是用于计数的起始索引,end 是要计数的最后一个索引。
challenge = 'thirty days of python' print(challenge.count('y')) # 3 print(challenge.count('y', 7, 14)) # 1, print(challenge.count('th')) # 2`
- endswith():检查字符串是否以指定结尾结尾
challenge = 'thirty days of python' print(challenge.endswith('on')) # True print(challenge.endswith('tion')) # False
- expandtabs():用空格替换制表符,默认制表符大小为 8。它需要制表符大小参数
challenge = 'thirty\tdays\tof\tpython' print(challenge.expandtabs()) # 'thirty days of python' print(challenge.expandtabs(10)) # 'thirty days of python'
- find():返回第一次出现的子串的索引,如果没有找到则返回-1
challenge = 'thirty days of python' print(challenge.find('y')) # 16 print(challenge.find('th')) # 17
- rfind():返回最后一次出现的子串的索引,如果没有找到则返回-1
challenge = 'thirty days of python' print(challenge.rfind('y')) # 5 print(challenge.rfind('th')) # 1
- format():将字符串格式化为更好的输出
有关字符串格式化的更多信息,请查看此链接first_name = 'Asabeneh' last_name = 'Yetayeh' age = 250 job = 'teacher' country = 'Finland' sentence = 'I am {} {}. I am a {}. I am {} years old. I live in {}.'.format(first_name, last_name, age, job, country) print(sentence) # I am Asabeneh Yetayeh. I am 250 years old. I am a teacher. I live in Finland.radius = 10 pi = 3.14 area = pi * radius ** 2 result = 'The area of a circle with radius {} is {}'.format(str(radius), str(area)) print(result) # The area of a circle with radius 10 is 314
- index():返回子字符串的最低索引,附加参数指示开始和结束索引(默认 0 和字符串长度 - 1)。如果未找到子字符串,则会引发 valueError。
challenge = 'thirty days of python' sub_string = 'da' print(challenge.index(sub_string)) # 7 print(challenge.index(sub_string, 9)) # error
- rindex():返回子字符串的最高索引,附加参数指示起始和结束索引(默认 0 和字符串长度 - 1)
challenge = 'thirty days of python' sub_string = 'da' print(challenge.rindex(sub_string)) # 8 print(challenge.rindex(sub_string, 9)) # error
- isalnum():检查字母数字字符
challenge = 'ThirtyDaysPython' print(challenge.isalnum()) # Truechallenge = '30DaysPython' print(challenge.isalnum()) # Truechallenge = 'thirty days of python' print(challenge.isalnum()) # False, space is not an alphanumeric characterchallenge = 'thirty days of python 2019' print(challenge.isalnum()) # False
- isalpha():检查所有字符串元素是否都是字母字符(az 和 AZ)
challenge = 'thirty days of python' print(challenge.isalpha()) # False, space is once again excluded challenge = 'ThirtyDaysPython' print(challenge.isalpha()) # True num = '123' print(num.isalpha()) # False
- isdecimal():检查字符串中的所有字符是否都是十进制(0-9)
challenge = 'thirty days of python' print(challenge.isdecimal()) # False challenge = '123' print(challenge.isdecimal()) # True challenge = '\u00B2' print(challenge.isdigit()) # False challenge = '12 3' print(challenge.isdecimal()) # False, space not allowed
- isdigit():检查字符串中的所有字符是否都是数字(0-9 和一些其他数字的 unicode 字符)
challenge = 'Thirty' print(challenge.isdigit()) # False challenge = '30' print(challenge.isdigit()) # True challenge = '\u00B2' print(challenge.isdigit()) # True
- isnumeric():检查字符串中的所有字符是否都是数字或数字相关(就像 isdigit() 一样,只接受更多符号,如 ½)
num = '10' print(num.isnumeric()) # True num = '\u00BD' # ½ print(num.isnumeric()) # True num = '10.5' print(num.isnumeric()) # False
- isidentifier():检查一个有效的标识符——它检查一个字符串是否是一个有效的变量名
challenge = '30DaysOfPython' print(challenge.isidentifier()) # False, because it starts with a number challenge = 'thirty_days_of_python' print(challenge.isidentifier()) # True
- islower():检查字符串中的所有字母字符是否均为小写
challenge = 'thirty days of python' print(challenge.islower()) # True challenge = 'Thirty days of python' print(challenge.islower()) # False
- isupper():检查字符串中的所有字母字符是否都是大写
challenge = 'thirty days of python' print(challenge.isupper()) # False challenge = 'THIRTY DAYS OF PYTHON' print(challenge.isupper()) # True
- join():返回一个连接的字符串
web_tech = ['HTML', 'CSS', 'JavaScript', 'React'] result = ' '.join(web_tech) print(result) # 'HTML CSS JavaScript React'
web_tech = ['HTML', 'CSS', 'JavaScript', 'React'] result = '# '.join(web_tech) print(result) # 'HTML# CSS# JavaScript# React'
- strip():从字符串的开头和结尾删除所有给定的字符
challenge = 'thirty days of pythoonnn' print(challenge.strip('noth')) # 'irty days of py'
- replace():用给定的字符串替换子字符串
challenge = 'thirty days of python' print(challenge.replace('python', 'coding')) # 'thirty days of coding'
- split():拆分字符串,使用给定的字符串或空格作为分隔符
challenge = 'thirty days of python' print(challenge.split()) # ['thirty', 'days', 'of', 'python'] challenge = 'thirty, days, of, python' print(challenge.split(', ')) # ['thirty', 'days', 'of', 'python']
- title():返回标题大小写的字符串
challenge = 'thirty days of python' print(challenge.title()) # Thirty Days Of Python
- swapcase():将所有大写字符转换为小写,将所有小写字符转换为大写字符
challenge = 'thirty days of python' print(challenge.swapcase()) # THIRTY DAYS OF PYTHON challenge = 'Thirty Days Of Python' print(challenge.swapcase()) # tHIRTY dAYS oF pYTHON
- startswith():检查字符串是否以指定字符串开头
challenge = 'thirty days of python' print(challenge.startswith('thirty')) # Truechallenge = '30 days of python' print(challenge.startswith('thirty')) # False
Python 30天:第四天 -- 字符串相关推荐
- Python基础总结(四) 字符串
目录 第四章 字符串 一.字符串格式问题及转义字符: 二.字符串的常见操作: (一)字符串的接拼: (二)字符串索引: (三)字符串分片: (四)字符串的不可变性: (五)字符串大小写转换方法: ( ...
- 1900页Python系列PPT分享四:字符串与正则表达式(109页)
总体说明:本套PPT共约1900页,包含董付国老师Python系列图书<Python程序设计基础>(2017年7月第5次印刷).<Python程序设计(第2版)>(2017年9 ...
- Python使用集合运算检测密码字符串的安全强度
封面图片:<Python程序设计基础与应用>(ISBN:9787111606178),董付国,机械工业出版社 图书详情: ============= 密码字符串的安全强度不仅取决于字符串长 ...
- Python按元组中第一个字符串升序第二个字符串降序排序
问题描述:假设有一个列表,里面包含若干元组,每个元组中有两个字符串,现在要求对列表中的元组进行排序,排序规则为:第一个字符串升序,如果第一个字符串相同则按第二个字符串降序. 参考代码: 运行结果: - ...
- 自学python第四课——字符串运算符、字符串内置函数、字符串常用方法总结
第四课 字符串 单.双.三引号 直接赋值和用 input 赋值: "+"号和"*"号在字符串中的使用 in 和 not in 字符串的格式化 r 保留原格式,即 ...
- 实验四,字符串的基本操作(Python,头歌)
第1关:字符串的拼接:名字的组成 任务描述 本关任务是将两个不同的字符串,拼接形成一个字符串,并将新字符串输出来.字符串或串(String)是由数字.字母.下划线组成的一串字符.在 Python 中, ...
- python string length_自学Python:第四篇字符串
字符串的基本操作 在Python中有两个字符串基本运算 1 加法连接 2 数乘 在javascript只有+加法字符连接 字符串的计算长度 在Python使用内置方法 len() 在javascrip ...
- python学习之第四课时--运算符
python学习之第四课时--运算符 运算符 1.算数运算 运算符 描述 实例 a=10,b=20 = 加,两个对象相加 a+b输出30 - 减,一个数减去另一个数 a-b输出-10 * 乘,两个数相 ...
- Python精确指南——第四章-部署和技巧
4 Python工程打包部署 Python程序在提供给用户使用时,要脱离Python开发环境运行,此时,需要对python工程进行打包. 常用的Python打包工具有PyInstaller ...
最新文章
- IC/FPGA笔试题分析(六)用16bit加法器IP核实现8bit乘法运算(文末彩蛋)
- 批处理相对路径51CTO自动领豆(Python)
- 杂项相关工具的使用方法(边刷题边更新...)
- wxWidgets:wxGenericDirCtrl类用法
- 研发和人力资源发展模式对比研究
- 让Windows7 x64 IIS7支持32位应用程序
- Windows2003 安装MVC4 环境的步骤
- oc渲染器中文手册_C4D·OC高级渲染视频教程,带你玩转质感渲染
- 使matlab2018支持使用VS2019编译
- Pajek常用方法保姆级操作指南——社会网络分析
- 计算机卡住了怎样恢复,电脑频繁假死怎么办 电脑死机数据恢复
- python psutil模块 硬盘厂家芯片型号_python第三方模块—psutil模块
- Python-集合 字典-set dict fronzenset
- 标准立方米的单位换算
- ifstat网络流量监控之/proc/net/dev文件
- Android有用代码(一)
- 基于Java的Minecraft游戏后端自定义插件 05事件监听器
- git 分支教程小游戏
- 【GlobalMapper精品教程】021:利用控制点校正栅格图像
- 数据可视化 为业务提供决策建议
热门文章
- ati显卡驱动的安装 linux,恭喜自己 ati显卡驱动安装成功
- oracle数据库连接游标超出,Oracle数据库游标连接超出解决方案
- html魔塔编辑器,migration.html
- 2022-2028中国澄清添加剂市场现状研究分析与发展前景预测报告
- 亚马逊云计算服务器在哪,亚马逊云服务(AWS)的“服务器型号“已近400种
- 仿百度壁纸client(六)——完结篇之Gallery画廊实现壁纸预览已经项目细节优化...
- 微信h5游戏模板:测试问答大冒险,真假朋友大考验
- [论文总结] 中国工科生常见英文写作问题总结
- 编码方式的简介(ASCII, LATIN-1, UTF-8/16/32)
- Nginx和Tomcat区别
- Python基础总结(四) 字符串