字符串(str):表示方式,级连字符串,字符串的切片取值,字符串的常用方法,upper(),lower(),split().len(),isdigit(),isnumeric(),cout()

字符串(str)

字符串是字符的不可变序列

字符串的表示方式

  • 使用单引号(') 例:a='str'

  • 使用双引号("") 例:a=”hello word“

  • 使用三引号(""" """) 例:a=""" hello world""",允许多行

>>> a='str'
>>> a
'str'
>>> a="hello world"
>>> a
'hello world'
>>> a="""
... ae
... hello
... """
>>> a
'\nae\nhello\n'

级连字符串

如果把两个字符串相邻放着,他们会被python自动级连

a = "hello",'world'
print(a)
输出:('hello', 'world')

原样输出引号里面的内容

>>> a=r"hello world\n hunan"    #r表示不转义,作为原始字符串输出
>>> print(a)
hello world\n hunan

字符串的切片取值

>>> str1 = "abcde"
>>> print(str1[3])
d
>>> print(str1[-2])
d
​
通过下标切片
#str[start:end:step])
# step 默认为1,每几步取一个值
#1、如果step为正表示从左到右截取,如果step为负,表示从右到左截取
#2、确认start和end的位置
#3、确认step的步长是多少
str1="abcdefghijk"
print(str1[3:])
print(str1[:7])
print(str1[3:5])
print(str1[3:8:2])
print(str1[-7:1:-2])
输出:
defghijk
abcdefg
de
dfh
ec

字符串的常用方法

判断系列(ture/false)

 

str1 = "123450"
str2 = "123一二三"
str3 = "abc450"
str4 = "hello"
print(str1.isdigit())    #是不是只包含数字1、①
print(str2.isnumeric())    #是不是只包含数字1、一
print(str3.istitle())    #是不是标题,首字母大写就是
print(str4.istitle())
输出为:
True
True
False
False

查找统计类

>>> len("shdsjkf")
7
>>> len("shdsjkf中国")
9
>>> 'dhjfsasdaa'.count("a")
3
>>> 'dhjfsasdaa'.count("aa")
1
>>> 'dhjfsasdaa'.count("aa",7)    #从第七位开始查找有几个aa
1
>>> 'hfdjkskja'.index("a")
8
>>> 'hfdjkskja'.index("aa")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> 'hfdjkskja'.find("a")    #find 比index好一点,index没有直接报错,find返回-1
8
>>> 'hfdjkskja'.find("aa")
-1

转换类

 

>>> a = "hello"
>>> print(a.upper())
HELLO
>>> print(a.lower())
hello
>>> print(a.title())
Hello World
>>> print(a.swapcase())
HELLO
>>>msg = "ab**5%ef"
>>>print(msg.replace("*","#").replace("%","#"))
ab##5#ef
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值