python learning 字符串方法

一、重点掌握的6种字符串方法:

1、join命令

功能:用于合并,将字符串中的每一个元素按照指定分隔符进行拼接

程序举例:

seq = ['1','2','3','4']
sep = '+'
v = sep.join(seq)
print(v)

test = "学习要思考"
t = '***'
v = t.join(test)
print(v)

 2、split命令

功能:与join相反,将字符串拆分为序列

test = '1+2+3+4+5'
v = test.split('+')
print(v)

test = '/usr/bin/env'
v = test.split('/')
print(v)

3、find命令

功能:在字符串中寻找子串。如果找到,就返回子串的第一个字符索引,否则返回-1.

test1 = 'with a moo-moo here, and a moo-moo there'
v1 = test1.find('moo')
print(v1)

test2 = "Monty Python's Flying Circus"
v2 = test2.find('Monty')
v3 = test2.find('Python')
v4 = test2.find('Flying')
v5 = test2.find('Zirquss')
print(v2)
print(v3)
print(v4)
print(v5)

可以指定搜索起点和终点

test = '### Get rich now!!! ###'
v = test.find('###', 1)
v1 = test.find('!!!')
v2 = test.find('!!!', 0, 16)
print(v)
print(v1)
print(v2)

4、strip命令:

功能:将字符串开头和结尾的空白(不包括中间的空白)删除,或者删除指定字符

test = '*** smart * fast * strong!!! ***'
v = test.strip(' *!')
print(v)

names = ['gumby', 'smith', 'jones']
name = 'gumby '
if name in names:
    print('Found it')
else:
    print('Not exist')
if name.strip() in names:
    print('Found it')

5、upper命令和lower命令:

test = "aLex"
v1 = test.upper()
v2 = test.lower()
print(v1)
print(v2)

二、字符串常见四种应用:

1、索引,下标 获取字符串中的某个字符

test = "alex"
v = test[2]
print(v)

2、切片,索引范围  0 =<  <1

test = "alex"
v = test[0:2]
print(v)

3、len获取当前字符串中由几个字符组成

test = "alex"
v = len(test)
print(v)

test = "圣诞节爱范娜"
index = 0
while index < len(test):
    v = test[index]
    print(v)
    index += 1
print('=======')

4、for循环:(非常重要)
for 变量名 in 字符串:
      变量名
for循环,索引,切片

test = "圣诞节爱范娜"
for item in test:
    print(item)

range命令:帮助创建连续数字,,通过设置步长来指定不连续数字

v = range(0,100)
for item in v:
    print(item)

v = range(0,10,2)
for item in v:
    print(item)

************例题:将文字,对应的索引打印出来**************

test = input(">>>")
v = range(0,len(test))
for item in v:
    print(item,test[item])

*********************

 注意:

********************************************
字符串一旦创建,不可修改
一旦修改或者拼接,都会造成重新生成字符串
********************************************

原文地址:https://www.cnblogs.com/dylee/p/10603704.html