Python学习第八天

字符串

是Python中的基本数据类型,是不可变序列。

字符串的查询

  1. index()方法
    可以设置startend,范围是[start,end)
    查找子串第一次出现的位置,若不存在,抛出ValueError。
s = "hello world!"
p1 = s.index('llo')
print(p1)
p2 = s.index('la')
print(p2)

####
2
Traceback (most recent call last):
    p2 = s.index('la')
ValueError: substring not found
  1. rindex()方法
    查找子串最后一次出现的位置,若不存在,抛出ValueError
s = "hello world!"
p1 = s.rindex('l')
print(p1)
p2 = s.rindex('la')
print(p2)

####
Traceback (most recent call last):
    p2 = s.rindex('la')
ValueError: substring not found
9
  1. find()方法
    查找子串第一次出现的位置,若不存在,返回-1
s = "hello world!"
p1 = s.find('l')
print(p1)
p2 = s.find('la')
print(p2)

####
2
-1
  1. rfind()方法
    查找子串最后一次出现的位置,若不存在,返回-1
s = "hello world!"
p1 = s.rfind('l')
print(p1)
p2 = s.rfind('la')
print(p2)

####
9
-1

大小写转换

不改变原字符串。

  1. upper()方法
    把所有字符转换成大写。
s = 'hello'
print(s.upper())

####
HELLO
  1. lower()方法
    把所有字符转换成小写。
s = 'hello'
print(s.upper().lower())

####
hello
  1. swapcase()方法
    把大写字符转成小写字符,小写字符转换成大写字符。
s = 'heLLoHi'
print(s.swapcase())

####
HEllOhI
  1. capitalize()方法
    把第一个字符转换成大写,其他字符都是小写。
s = 'heLLoHi'
print(s.capitalize())

####
Hellohi
  1. title()方法
    每个单词的首字符大写,其他小写。
s = 'heLLoHi wORLd'
print(s.title())

####
Hellohi World

字符串内容对齐

字符串的分割

s = 'I like cpp'
l = s.split()
print(l)

####
['I', 'like', 'cpp']

判断字符串

字符串的替换

s = 'I like cpp'
ns = s.replace("like", 'fuck')
print(ns)

####
I fuck cpp

字符串的合并

l = ['hello', 'cpp', 'java']
print(','.join(l))
t = ('hello', 'python', 'vb')
print(''.join(t))

print('@'.join('Python'))

####
hello,cpp,java
hellopythonvb
P@y@t@h@o@n
posted @ 2021-02-04 12:24  sxhyyq  阅读(40)  评论(0编辑  收藏  举报