常用函数

一、基本函数

# join #       '_'.join("asdfasdf")
# split  
# find
# strip
# upper
# lower
# replace

1 .join() #将序列中的元素以指定的字符连接生成一个新的字符串

test = '大河向东流'
print(test)
v = '*'.join(test) #将*号加入到test字符串的各子字符串之间
print(v)

输出结果:

大河向东流
大*河*向*东*流

2 .split() #分隔符切片 string,如果 num有指定值,则仅分隔 num 个子字符串

test = 'daishfojisjdadasfdsddd'
s3 = test.split('s')
s4 = test.split('s',3) #将test字符串以s为分隔符分割成3次
print(s3)
print(s4)

输出结果:

['dai', 'hfoji', 'jdada', 'fd', 'ddd']
['dai', 'hfoji', 'jdada', 'fdsddd']

3 .find() #在字符串中寻找指定字符的位置

a = 'Titleleitttt'
b = a.find('lei') #寻找字符lei的位置
print(b)

输出结果:5

4 .strip() #移除字符串头尾指定的字符(默认为空格)

test = '0000this  is wonderful000'
v1 = test.strip('00')
print(v1)

输出结果:this  is wonderful

5 大小写

.islower() #判断是否全部是小写

.lower() #转换为小写

.isupper #判断是否全部是大写

.upper() #转换为大写

复制代码
test = 'CONSIDER'
test2 = 'consider'
v1 = test.islower() #判断test字符串是否为小写
v2 = test.lower() #将test字符串转换为小写
v3 = v2.islower() #判断V3字符串是否为小写
n1 = test2.isupper()
n2 = test2.upper()
n3 = n2.isupper()
print(v1,v2,v3)
print(n1,n2,n3)
复制代码

输出结果:

False consider True
False CONSIDER True

6 .replace() #把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次

test = 'daexdjiexdjiolkjexdddd'
v1 = test.replace('ex','OK')
v2 = test.replace('ex','NO2',2) #只能替换两次
print(v1)
print(v2)

输出结果:

daOKdjiOKdjiolkjOKdddd
daNO2djiNO2djiolkjexdddd

二、for循环及获取字符、长度,切片

1. for 变量名 in 字符串: #可以遍历任何序列的项目,如一个列表或者一个字符串

for letter in 'Python':
    print(letter)

输出结果:

P
y
t
h
o
n

2 [] #获取索引,下标,获取字符串中的某一个字符。中括号填入数字为起始位置

test = '我没有钱,你很有钱'
v1 = test[2]
print(v1)

输出结果:有

3、for与while比较

test = 'Python'
num = 0
while num < len(test) :
    v = test[num] #通过[]索引获取字符串中字符
    print(v)
    num += 1 #叠加1

输出结果:

P
y
t
h
o
n

4、获取字符

[x]索引第X位后的字符,负数为从右开始

[x:y] #截取字符串中的一部分

test = '我没有钱,你有很多钱'
v1 = test[0:2]
v2 = test[0:-2]
v3 = test[2]
v4 = test[-2]
print(v1)
print(v2)
print(v3)
print(v4)

输出结果:

我没
我没有钱,你有很

5、 len() #获取长度

test = '我没有钱,你有很多钱'
v = len(test)
print(v)

输出结果:10

6、 range() #取值范围

r1 = range(0,100,20) #0-100中,每20选一个
for num in r1 :
    print(num)

输出结果:

0
20
40
60
80

三、字符信息

字符串一旦创建,不可修改

一旦修改或者拼接,都会造成重新生成字符串

test = 'yingxionglianmeng'
age = '5'
info = test + age
print(info)

输出结果:yingxionglianmeng5

原文地址:https://www.cnblogs.com/lishuangtu/p/8876315.html