字符串(string):‘ * ‘,“*“ ,“‘*‘‘

源字符串不可变;常见由字母/数字/汉字/符号组成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值