字符串是 Python 中最常用的数据类型,可以使用引号(‘或”)来创建字符串。具体相关操作可以去网页上学习
英文:https://www.tutorialspoint.com/python/python_strings.htm
中文:http://www.runoob.com/python/python-strings.html
1、字符串的定义和获取:使用下标
# Hello World program in Python
# -*- coding: utf8 -*-
import os,sys
say="hello!Morning"
i=0
#字符串操作
while i < len(say):
print(i, " = ",say[i])
i=i+1
运行结果
2、使用切片方式
#!python
# -*- coding: utf8 -*-
import os,sys
say="hello!Morning"
print("len",len(say))
print(say[0:5])
print(say[5:])
print(say[5:13])
print(say[0:-7])
print(say[:-7])
运行结果
3、字符串连接:+
#!python
# -*- coding: utf8 -*-
import os,sys
say="hello!"
say=say+"Morning"
print("len",len(say))
print(say[0:5])
print(say[5:])
print(say[5:13])
print(say[0:-7])
print(say[:-7])
运行结果
4、字符串长度获取:len
#!python
# -*- coding:utf8 -*-
import os,sys
say="hello!"
say1=say+"Morning"
print("len",say1,len(say1))
say2="%s%s"%(say,"Morning")
print("len",say2,len(say2))
say3="len %s %d"%(say2,len(say2))
print(say3)
运行结果
5、字符串替换:replace
string.replace(str1, str2, num=string.count(str1))
把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次.
#!python
# -*- coding:utf8 -*-
import os,sys
say="hello!"
say1=say+"Morning"
print("len",say1,len(say1))
say1=say1.replace("hello","Hello ")
print("len",say1,len(say1))
b=say1.find("Morning")
c=say1[b:]
print("len",c,len(c))
运行结果