python字符串变量相关知识点
z • 2020 年 07 月 22 日
Loading...
# python中双引号和单引号表达的意思一样。
**1.将所选字符串中的首字母大写。即capitalize()的使用方法。**
**注:数值类型,字符串类型,元组这三种类型的变量是不可变的。**
message=“life is short,you need python”
print(message.capitalize())
**reslut>Life is short,you need python**
------------
**2.统计特定字符在当前字符串中出现的次数。即count()的使用方法。**
**统计字母‘o’出现的次数:**
message=“life is short,you need python”
print(message.count(“o”)
**reslut> 3**
------------
**3.判断所选字符串开头或结尾是否是某个字符时。** 开头:startswith 结尾:endswith 若是以某个字符开头或结尾,则反馈结果为**True**,如果不是则反馈为**Flase**
**判断‘l’是否为当前字符串的开头和结尾字符。**
message="life is short,you need python"
print(message.startswith('l'))
print(message.endswith('l'))
**reslut>True**
**reslut>Flase**
------------
**4.查找所选字符在字符串中的起始位置(比实际位置小1),若所选字符串不存在于当前字符串中,则反馈-1. **
**find()**
**查找s在当前字符串中的位置。** **存在情况时:**
message=“life is short,you need python”
print(message.find('s'))
**result>6 **
**当不存在与当前字符串时**
message=“life is short,you need python
print(message.find('w'))
**result>-1**
------------
**5.将当前字符串中的字母全部变成大写或者小写。大写:upper(),小写:lower()。**
**大写示范:**
message=“Life is short,you need python"
print(message.upper())
**result=LIFE IS SHORT,YOU NEED PYTHON **
**小写示范:**
message=“Life is short,you need python"
print(message.lower())
**result>life is short,you need python**
------------
**6.替换所选字符串中的某个字符。replace()**
**全部替换:**
message=“life is short,you need python"
print(message.replace('o','a')
**result>life is shart,yao need pythan**
**替换指定数量的:**
**replace(‘要被替换的字符’,‘新的字符’,‘替换次数’)**
message=“life is short,you need python"
print(message.replace('o','a',2)
**result>life is shart,yao need python**
------------
**7.对字符类型进行检测,type()**
**int为整数类型,float为小数类型,str为字符串类型。**
data=“123”
print(type(data2))
**reslut>str**
------------