python中astr是啥_Python学习之路——字符串1

1字符串

字符串类型是Python里面最常见的类型。我们可以通过在引号(‘ 和 “ 的作用是一样的)间包含字符的方式创建它。字符串是一种标量,而且是不可变类型。字符串是由独立的字符组成的,这些字符可以通过切片操作顺序的访问。

1.1字符串的创建和赋值

>>> aStr = 'hello world'

>>> another = "hello csdn"

>>> aStr

'hello world'

>>> another

'hello csdn'

>>> s = str(range(5))

>>> s

'[0, 1, 2, 3, 4]'

>>>

1.2访问字符串的值

Python中没有字符这种类型,而是用长度为1的字符串来表示。用切片操作可以得到字符或子串。

>>> aStr

'hello world'

>>> aStr[2]

'l'

>>> aStr[2:]

'llo world'

1.3改变字符串

你可以通过给一个变量重新赋值来改变字符串。

>>> aStr

'hello world'

>>> aStr = aStr[:6] + ' python'

>>> aStr

'hello python'

>>>

字符串类型是不可变的,所以你要改变一个字符串就必须通过创建新的字符串对象来实现。

1.4删除字符和字符串

字符串是不可变的,所以你不可以删除一个字符串的某个字符,你能做的就是把整个字符串都删除。若你想达到删除某个字符的效果,可以把剔除了不需要部分的字符串组合起来成为一个新串。比如我要删掉‘o’,可以通过del语句来删除字符串。

>>> aStr = 'hello man'

>>> aStr = aStr[:4] + aStr[5:]

>>> aStr

'hell man'

>>> del aStr

2字符串和操作符

2.1标准类型操作符

>>> str1 = 'abc'

>>> str2 = 'def'

>>> str3 = 'kmn'

>>> str1 < str2

True

>>> str1 != str2

True

>>> str1 < str3 and str2 == 'def'

True

>>>

字符串之间是按照ASCII值得大小来比较的。

2.2序列操作符切片

正向索引:

>>> str = 'abcdefg'

>>> str[0:3]

'abc'

>>> str[2:5]

'cde'

>>>

逆向索引:>>> str[-6:-1]

'bcdef'

>>> str[-8:-1]

'abcdef'

>>>

默认索引:若开始索引或介绍索引没有指定,则分别以字符串的第一个和最后一个索引值为默认值,若两者都没指定,则返回整个字符串

>>> str[:4]

'abcd'

>>> str[4:]

'efg'

>>> str[:]

'abcdefg'

>>>

2.3成员操作符(in, not in)

成员操作符用于判断一个字符或者一个子串是否出现在另一个字符串中。出现则返回Ture ,否则返回False

>>> 'bc' in 'abcd'

True

>>> 'n' in 'abcd'

False

>>> 'dd' not in 'abcd'

True

>>>

2.4 连接符(+)

连接符可以将两个字符串连接起来形成一个新的字符串。

>>> 'this is str1' + ' this is str2'

'this is str1 this is str2'

>>> s = 'xxx' + ' ' + 'is a good' + ' ' + 'student'

>>> s

'xxx is a good student'

这种连接叫做运行时刻连接,还有一种连接是编译时连接(不常用,看个人习惯)

>>> text = 'hello' 'world!'

>>> text

'helloworld!'

>>>

原文:http://blog.csdn.net/u012088213/article/details/44656051

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值