变量和字符串
- 一、字符串的大小写的五种转换函数
- 1、str.lower() 转换为小写
- 2、str.upper() 转换为大写
- 3、str.capitalize() 转换为首字母大写
- 4、str.title() 转换为每个单词首字母大写
- 5、str.swapcase() 转换为大小写互换
- 6、代码
- 二、格式化 -- 字符串
- 三、制表符与换行符
- 1、制表符
- 2、换行符
- 四、删除空白
- 1、str.lstrip() 删除左侧空白
- 1、str.rstrip() 删除右侧空白
- 1、str.strip() 删除俩侧空白
- 五、查找字符串
- 1、 str.find()
- 2、语法:str.find(目标串,[开始位置],[结束位置])
- 3、代码
- 六、字符串替换
- 1、str.replace()
- 2、语法:str. replace(原始串,目标串,[替换次数])
- 3、示例
一、字符串的大小写的五种转换函数
1、str.lower() 转换为小写
format()函数也支持数字格式化
2、str.upper() 转换为大写
3、str.capitalize() 转换为首字母大写
4、str.title() 转换为每个单词首字母大写
5、str.swapcase() 转换为大小写互换
6、代码
下面展示一些 内联代码片
。
// """
大-小 str.lower
小-大 str.upper
字符串首字母大写 str.capitalize
每个单词首字母大写 str.title
大小互换 str.swapcase
"""
str1 = "NBA"
str2 = "abc"
str3 = "this is my bag"
str33 = "My fried is nice"
str4 = str.lower(str1)
print(str4)
print(str1.lower())
str5 = str.upper(str2)
print(str5)
str6 = str.capitalize(str2)
print(str6)
str7 = str.title(str3)
print(str7)
print("michale jason".title())
str8 = str.swapcase(str33)
print(str8)
二、格式化 – 字符串
函数表达式:str.format()
示例1:"{}{}{}happy".format("I","am","so") 将产生:"I am happy"
示例2:"{2}{1}{0}happy".format("I","am","so") 将产生:"I am happy"
# 格式化 -- 数字
format()函数也支持数字格式化
示例1:format(1234.567,‘0.2f’)#小数保留2位
示例2:format(1234.567,‘,’)#千分位分隔符
三、制表符与换行符
1、制表符
制表符是指增加字符的缩进,在字符串中使用 \t
2、换行符
换行符是指为字符串换行输出,在字符串中使用\n
四、删除空白
1、str.lstrip() 删除左侧空白
1、str.rstrip() 删除右侧空白
1、str.strip() 删除俩侧空白
五、查找字符串
1、 str.find()
2、语法:str.find(目标串,[开始位置],[结束位置])
3、代码
下面展示一些 内联代码片
。
// str.find()是查找指定字符在字符串中的位置,
第一个参数是被查找的字符,
第二个是开始位置,
第三个是结束位置,
不指定位置就默认第一个开始,不存在就会返回-1
//不指定位置查找,默认从第一个开始
str9 = "this is a perfect day, it is really nice and warm"
res1 = str9.find('z')
print(res1)
//指定位置查找,第一个字母从下标为0开始数
str11 = "this is a perfect day, it is really nice and warm"
res1 = str11.find('s',0,20)
print(res1)
六、字符串替换
1、str.replace()
2、语法:str. replace(原始串,目标串,[替换次数])
3、示例
下面展示一些 内联代码片
。
// A code block
var foo = 'bar';
str10 = "this is a perfect day, it is really nice and "
res2 = str10.replace('is','was')
print(res2)
str11 = 'aabbcccccddd'
res3 = str11.replace('a','b[0]')
print(res3)