源字符串不可变;常见由字母/数字/汉字/符号组成
1.字符串查寻(str):str[索引位置]:
country='Washington America'
print(country[0])
输出:W
print(country[7])
输出:t
print(country[11])
输出:A
2.str元素字母由小写改成大写:str.upper();字母改成小写str.lower();英文单词首字母改成大写str.title():
country='Washington America'
str =country.upper()
print(str)
输出:WASHINGTON AMERICA
str1=country.lower()
print(str1)
输出:washington america
name=''the united kingdom''
str=name.title()
print(str)
输出:The United Kingdom
3.str元素删除/替换:str.replace('字符串元素','替换元素'):
country='Washington America'
str=country.replace('Washington','New York')
print(str)=New York America
4.str切割:str[索引开始位置:中止索引位置:步长];str.split('切割位置')由字符串变成列表:
country='Washington America'
str=country[1:10]
print(str)
输出:ashington
str=country[1:10:3]
print(str)
输出:ait
list=country.split(' ')
list=country.split(' ')
print(list)
输出:['Washington', 'America']
5.判断:str开头/结尾以' * 'start|(end)with(' * ');str.isgidit()/str.isalpha()/str.isalnum()字符串是否由数字/字母/数字、字母组成:
country='Washington America'
print(country.startswith('W'))
输出:True
print(country.startswith('A'))
输出:False
print(country.endswith('a'))
输出:True
print(country.endswith('t'))
输出:False
country='WashingtonAmerica'
print(country.isalpha())
输出:True
print(country.isalnum())
输出:False
6.字符串元素查找:str.count('*')统计字符串有多少个*,没有报none;str.find('*')查找字符串中第一次出现'*'索引位置,没有报-1;str.index('*')跟find功能一样但没有查到结果直接报错:
country='Washington America'
print(country.count('a'))
输出:2
print(country.count('z'))
输出:0
print(country.find('a'))
输出:1 #索引位置
print(country.find('z'))
输出:-1
print(country.index('a'))
输出:1 #索引位置
print(country.index('z'))
输出:Traceback (most recent call last):
File "D:\pythonProject1\day5.py", line 15, in <module>
print(country.index('z'))
ValueError: substring not found
7.str.strip()/str.lstrip()/str.rstrip()字符串两边/左/右空白(/n)去除.
country=' Washington America '
print(country.strip())
输出:Washington America
print(country)
输出: Washington America
8.索引的获取:
s = '北京是中国的首都!'
for i in s:
print(s.index(i))
输出:
0
1
2
3
4
5
6
7
8
Process finished with exit code 0