版权声明:转载请注明出处: https://blog.csdn.net/qq_33757398/article/details/82592460
1.字符串
1)字符串可以用单引号或者双引号表示(创建)
2)字符串格式化-》使用操作符百分号(%)实现,使用方法与C中的printf函数相似,有多个输出参数时,用括号括起来,如果要输出百分号(%),就需要写两个百分号
hello = 'hello' # String literals can use single quotes
world = "world" # or double quotes; it does not matter.
print(hello) # Prints "hello"
print(len(hello)) # String length; prints "5"
hw = hello + ' ' + world # String concatenation
print(hw) # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatting
print(hw12) # prints "hello world 12"
打印结果:
hello
5
hello world
hello world 12
2)str对象不支持修改
3)转义字符(与C类似)
print('hello\nworld')
print('hello''\n''world')
print('\'hello\'\n\'world\'')
打印结果:
hello
world
hello
world
'hello'
'world'
2.基本操作函数
1)find()用于检测字符串中是否包含字符串str
str.find(str, beg=0, end=len(str))
2)join()用于将序列中的元素以指定字符连接成一个新字符串,对象必须是字符串
3)lower()用于将字符串中所有大写字符转换成小写
4)upper()用于将字符串中所有小写字符转换成大写
5)swapcase()用于将字符串中的大小写字符进行转换
6)replace()用于替换字符串中的字符串
7)split()通过指定分隔符对字符串进行切片
8)strip()用于移除字符串头尾指定的字符(默认为空格)
9)translate()根据参数table给出的表(包含256个字符)转换字符串的字符,将要过滤掉的字符放到del参数中
str.translate(table[, deletechars])
s="hello"
s1='heLLo'
print(s.capitalize()) #将字符串的首字母大写
print(s.upper()) #将字符串的字母全变成大写
print(s1.upper()) #若字符串中含有大写字母则保持不变
print(s.rjust(10)) #右对齐,填充空格
print(s.center(10)) #居中对齐,填充空格
print(s.replace('l','(L)')) #字符替换
print(' world'.strip()) #除去字符前面的空格
打印结果:
Hello
HELLO
HELLO
hello
hello
he(L)(L)o
world