Python字符串
Python的字符串是一种不可变的字符序列。同时支持索引,分片,遍历等操作。
创建
通过单引号,双引号,三引号都可以创建字符串!
s01 = 'China'
s02 = "China"
s03 = """China"""
s04 = '''China'''
s01 == s02 == s03 == s04
True
常见的操作
转义
方法 | 含义 |
---|---|
\t | 横向制表符 |
\b | 退格 |
\v | 纵向制表符 |
\' | 表示单引号 |
\" | 表示双引号 |
\\ | 表示反斜杠 |
\n | 换行 |
print("She\tcome\tfrom\tChina")
print("She\bcome\bfrom\bChina")
print("She\vcome\vfrom\vChina")
print("She\'come\'from\'China")
print("She\"come\"from\"China")
print("She\\come\\from\\China")
print("She\ncome\nfrom\nChina")
She come from China
ShcomfroChina
She�come�from�China
She'come'from'China
She"come"from"China
She\come\from\China
She
come
from
China
类型转换
通过str()可以将int类型转换成str类型
print(type(66666))
print(type(str(66666)))
<class 'int'>
<class 'str'>
拼接复制合并字符串
a="She ";b="come ";c="from ";d="china "
print(a+b+c+d)
print(a*4+b*3+c*2+d*1)
a = ["she come"];b =["from china"]
print(" ".join(a+b))
She come from china
She She She She come come come from from china
she come from china
拼接合并对比
import timeit
...: print(timeit.timeit("s ='';s += str(n for n in range(0,100000))",number=100000))
...: print(timeit.timeit("l =[];l.append(str(n for n in range(0, 100000)));s=''.join(l)",number=100000))
...:
0.12783753898111172
0.14433829998597503
提取字符串
通过偏移量可以提取想要的字符
info01="She come from China!"
print(info01[1])
print(info01[-1])
字符串的分片操作
字符串是支持分片操作的
pi="3.1415926535898"
print(pi[:])
print(pi[1:])
print(pi[:8])
print(pi[4:8])
print(pi[1:10:2])
3.1415926535898
.1415926535898
3.141592
1592
.4525
获取字符串的长度
通过内置函数len可以获取字符串的长度
len(pi)
分割字符串
#info02.split()
info02="She come from China and she lives in beijing ,She don't have any brothers or sisters"
info02.split("and")
info02.split(",")
path ='http://www.baidu.com/abcd/club'
namespace =path.split('//')[1].split('/')[0]
print(namespace)
url = path.split('//')[1].split('/')[1:]
print (url)
字符串的格式化
个人觉得format这种方式比%s那种更好一些
name = "zhangwen"
id = "007"
print("no data available for person with id:{}, name:{}.".format(id, name))
字符串的一些操作函数
info03="Lisa come from China, she don't have any brothers or sisters, she lives in singapore."
print(info03.startswith("China"))
print(info03.endswith("singapore"))
print(info03.find("she"))
print(info03.rfind("she"))
print(info03.count("she"))
print(info03.strip("."))
print(info03.title())
print(info03.upper())
print(info03.lower())
...等等
总结
首先字符串是不可变的,其次字符串的拼接很高效,最后字符串的格式化很常见!
网友评论