目录
打印字串
例子1 基本
print('hello world')
Hello World
例子2 带分隔符
print('hello', 'world', sep='-')
Hello-World
例子3 不同结尾
print('hello', 'world',end='.')
Hello World.
是否为空
例子1 字串为条件
my string = ""
if not mystring:
print("the string is empty.")
else:
print("the string is not empty.')
The string is empty.
例子2 是否等于
mystring = ""
if mystring == "":
print("the string is empty.")
else:
print("the string is not empty.")
The string is empty.
获取长度
例子1 获得长度
mystring = 'python examples'
length = len(mystring)
print('Length of the string is:', length)
Length of the string is: 15
例子2 获得空字串长度
mystring = ''
length = len(mystring)
print('length of the is:', length)
length of the is: 0
子串
例子1 找
mystring = 'pythonexamples.org'
substring=mystring[6:12]
print(substring)
exampl
例子2 结束位置大于长度
mystring = 'pythonexamples.org'
substring = mystring[6:35]
print(substring)
examples.org
例子3 负位置
mystring = 'pythonexamples.org'
substring = mystring[-15:-5]
honexample#mystring[18-15:18-5] where length of mystring is 18
例子4 没有开始或结束
mystring = 'pythonexamples.org'
substring = mystring[:]
print(substring)
pythonexamples.org#original
反转
例子1 Slicing
str = 'Welcome to Python Examples.'
reversed = str[::-1] #from start to end, -1: reverse
print(reversed)
例子2 For Loop
str = 'Welcome to Python Examples.'
reversed = ''
for c in str:
reversed = c + reversed #append in reverse order(left)
print(reversed)
D:\>python example.py
.selpmaxE nohtyP ot emocleW
例子3 While Loop
str = 'Welcome to Python Examples.'
reversed = ''
length = len(str) - 1
while length >= 0:
reversed = reversed + str[length]
length = length - 1
print(reversed)
D:\>python example.py
.selpmaxE nohtyP ot emocleW
例子4 List.reverse()
str = 'Welcome to Python Examples.'
str_list = list(str)
str_list.reversed()
reversed = ''.join(str_list)
print(reversed)
D:\>python example.py
.selpmaxE nohtyP ot emocleW
截取
例子1 结束位置
string1 = 'hello-world'
stop = 5#end position
slice_object = slice(stop) #[0,1,2,3,4]
result = string1[slice_object]
print(result)
hello
例子2 开始和结束位置
string1 = 'hello-world'
start = 2
stop=5
slice_object = slice(start, stop)
result = string1[slice_object]
print(result)
llo
例子3 开始,结束和步进
string1 = 'hello-world'
start = 2
stop = 9
step = 2
slice_object = slice(start, stop, step)
result = string1[slice_object]
print(result)
lowr
遍历
例子1 遍历
str = 'Hello! I am Robot. This is a Python example.'
splits = str.split()
for split in splits:
print(split)
例子2 清空并遍历
import re
str = 'Hello! I am Robot. This is a Python example.'
#clean string
pat = re.compile(r'[^a-zA-Z ]+')
str = re.sub(pat, '', str).lower()
splits = str.split()
for split in splits:
print(split)