1.1 字符串的基本操作
对序列的操作都适用于字符串,但字符串是不可变的,所以元素赋值和切片赋值都是非法的
1.2 设置字符串的格式
方法一: 使用%来设置字符串
| format = 'Hello, %s. %s enough for ya?' |
| values = ('world', 'Hot') |
| print(format % values) |
| > Hello, world. Hot enough for ya? |
方法二: 使用模板字符串(需要导入模块)
| from string import Template |
| tmp1 = Template("$test") |
| str1 = tmp1.substitute(test = 'yes') |
| print(str1) |
| > yes |
| tmpl = Template("Hello, $who! $what enough for ya?") |
| str1 = tmpl.substitute(who="Mars", what="Dusty") |
| print(str1) |
| > Hello, Mars! Dusty enough for ya? |
| str1 = "{} {} {}".format("1", "2", "3") |
| print(str1) |
| > 1 2 3 |
| str1 = "I am {}. What is your {}?".format("LMC", "name") |
| print(str1) |
| > I am LMC. What is your name? |
| str1 = "{1}, {0}, {2}".format("2", "1", "3") |
| print(str1) |
| > 1, 2, 3 |
| str1 = "{name} {be} {someone}".format(name = "bob", be = "is", someone = "a dog") |
| print(str1) |
| > bob is a dog |
更完整的设置字符串格式参考:Python基础教程p43
1.3 字符串函数
1.3.1 endswith 判断最后是否以特定字符串结尾
| str1 = 'I am a student' |
| print(str1.endswith('ent')) |
| print(str1.endswith('s')) |
| > |
| True |
| False |
本文作者:清澈的澈
本文链接:https://www.cnblogs.com/lmc7/p/17537320.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步