python中的字符串

一、在python中,字符串是不可变类型

通过以下代码说明:

>>> s = 'hello, world'
>>> id(s)
2108634288304
>>> s = 'hello, chenjun'
>>> id(s)
2108634548592

可以看到,改变字符串变量s的取值,其内存地址发生了变化,因此字符串是不可变数据类型。

二、字符串的操作:

字符串拼接(通过+来实现):

>>> s = 'hello'
>>> s = s + 'world'
>>> s
'helloworld'

字符串替换:

>>> s = 'hello, world'
>>> s.replace('world', 'chenjun')
'hello, chenjun'

字符串首字母大写:

>>> s = 'hello, world'
>>> s.capitalize()
'Hello, world'

字符串全变小写:

>>> s = 'HELLO'
>>> s.casefold()
'hello'

或者

>>> s = 'HELLO'
>>> s.lower()
'hello

字符串全变大写:

>>> s = 'hello'
>>> s.upper()
'HELLO'

字符串大写变小写,小写变大写:

>>> s = 'hEllo'
>>> s.swapcase()
'HeLLO'

将字符串变成标题格式:

>>> s = 'hello, world'
>>> s.title()
'Hello, World'

判断字符串是否是标题格式,返回True or False:

>>> s = 'hello, world'
>>> s.istitle()
False

判断字符串是否以某个指定字幕开头或结尾:

>>> s = 'hello, world'
>>> s.startswith('h') 
True
>>> s.endswith('h')
False

判断字符串是大写还是小写:

>>> s = 'hello, world'
>>> s.isupper()
False
>>> s.islower()
True

查字符串中某指定字符出现次数,可指定位置查询:

>>> s.count('l')
3
>>> s.count('l', 3, 11)  #空格和逗号算一个字符
2

查字符串中某指定字符的index,可指定位置查询:

>>> s = 'hello, world'  #默认从左向右查询,返回第一个坐标
>>> s.find('l')
2
>>> s.rfind('l')  #从右往左查询
10
>>> s.find('l',  3,  12) #指定位置查询
3

填充字符:

>>> s = 'hello, world'
>>> s.center(30, '=')   #填充使字符居中
'=========hello, world========='
>>> s.ljust(30, '=')     #填充使字符居左
'hello, world=================='
>>> s.rjust(30, '=')     #填充使字符居右
'==================hello, world'
>>> s.zfill(30) #从左填充,以0补充空位
'000000000000000000hello, world'

去空格:

>>> s = '  hello,  world  '
>>> s.strip()       #去左右空格
'hello,  world'
>>> s.lstrip()      #去左空格
'hello,  world  '
>>> s.rstrip()      #去右空格
'  hello,  world'

字符串格式化:

>>> s = 'hello, {}'.format('chenjun')
>>> s
'hello, chenjun'
>>> s = 'my name is {dic[name]}, I am {dic[age]} years old'.format(dic = dic)
>>> s
'my name is chenjun, I am 21 years old'

以上是一些基本的字符串操作案例。

原文地址:https://www.cnblogs.com/tarantino/p/10211416.html