乐之之

知而行乐,乐而行之,天道酬勤,学无止境。
字符串

一、字符串的输入输出

(一)输入input()

name = input("请输入你的名字:")
print(name)
print(type(name))

age = input("请输入你的年龄:")
print(age)
print(type(age))

--------------------------------------
张三
<class 'str'>
20
<class 'str'>

(二)格式化输出

name = "张三"
age = 20
heigth = 178.5

print("我的名字是%s"%name)
print("我今年%d岁了"%age)
print("我的身高是%.2f"%heigth)
print("大家好,我叫{},我今年{}岁,我的身高是{}".format(name,age,heigth))
print(f"大家好,我叫{name},我今年{age}岁,我的身高是{heigth}")

---------------------------------------------------------------------
我的名字是张三
我今年20岁了
我的身高是178.50
大家好,我叫张三,我今年20岁,我的身高是178.5
大家好,我叫张三,我今年20岁,我的身高是178.5

 

二、 下标(索引)

  • 下标又叫索引,就是编号。比如火车座位号,座位号的作用:按照编号快速找到对应的座位。
  • 索引是从0开始
var1 = "hello python"
print(var1[1])
print(var1[2])
print(var1[4])

-------------------------
e
l
o

 

三、切片

  • 根据索引值切
var = "hellopython"

print(var[0:5])        # 从下标为0开始,到5结束,5取不到
print(var[:5])          # 从下标为0开始,到5结束,5取不到
print(var[0:5:2])     # 从下标为0开始,到5结束,5取不到,步长为2
print(var[:])            # 全部拿取
print(var[5:11])       # 从下标为5开始,到11结束,11取不到
print(var[5:])           # 从下标为5开始,后面的全都要

----------------------------------
hello
hello
hlo
hellopython
python
python
  • 根据索引值切也可以从后往前切。
var = "hellopython"

print(var[-6:-1])             # 从-6开始,拿到-1,-1取不到
print(var[-1:-12:-1])       # 从-1到-12,倒着打印
print(var[-4::-1])            # 从-4开始,前面的都拿到,倒着打印

---------------------------------------------------------
pytho
nohtypolleh
typolleh

四、常用操作方法

(一)查找

  • 所谓字符串查找方法即是查找子串在字符串中的位置或出现的次数。

  1、find()

  • 检测某个字符串是否包含在这个字符串中,如果在,返回这个字符串开始的位置下标,否则则返回-1
# 字符串序列.find(子串,开始位置下标,结束位置下标)

var = "hello and python and hello world"

print(var.find("and"))         # 查找到and首字母下标
print(var.find("and",8,20))  # 查找到下标为8-20,and首字母下标
print(var.find("ors"))           # 查找ors,如果没有,则返回-1

---------------------------------------------------------
6
17
-1

  2、index():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则报异常。

# 字符串序列.index(子串,开始位置下标,结束位置下标)

var = "hello and python and hello world"

print(var.index("and"))        # 查找到and首字母下标
print(var.index("and",8,20)) # 查找到下标为8-20,and首字母下标
print(var.index("ors"))          # 查找ors,如果没有,则报错

------------------------------------------------
6
17
Traceback (most recent call last):
  File "E:\python_basics\第八节课--字符串\demo05.py", line 15, in <module>
    print(var.index("ors"))          # 查找ors,如果没有,则报错
ValueError: substring not found

  3、count():返回某个子串在字符串中出现的次数

  • 注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找。
# 字符串序列.count(子串,开始位置下标,结束位置下标)

var = "hello and python and hello world"

print(var.count("and"))        # 查看在字符串var中,and出现了多少次
print(var.count("ands"))       # 如果没有,则返回0次
print(var.count("and",8,20)) # 在一个区间内查找and出现的次数

--------------------------------------------------
2
0
1

(二)修改

  • 对字符串当中的内容进行修改

  1、replace():替换内容

  • 注意:替换次数如果超出子串出现次数,则替换次数为该子串出现次数。
var = "hello and python and hello world"
print(var.replace("and",""))   # 将里面所有的and替换为和
print(var.replace("and","",1))   # 将and替换为和,只替换一次
print(var.replace("and","",3))   # 将and替换为和,超出and次数时,只替换该字符串出现的次数

---------------------------------------
hello 和 python 和 hello world
hello 和 python and hello world
hello 和 python 和 hello world

  2、split():按照指定字符分割字符串

  • 注意:num表示的是分割字符出现的次数
# 字符串序列.split(分割字符出现的次数)

var = "hello and python and hello world"

print(var.split("and"))    # 以and为界,分隔开其他字符串,返回一个列表
print(var.split("and",1))  # 以and为界,分隔开其他字符串,只分割一次,返回一个列表

---------------------------------------------
['hello ', ' python ', ' hello world']
['hello ', ' python and hello world']

  3、join():用一个字符或子串合并字符串,即是将多个字符串合并成为一个新的字符串

  • 注意:数据类型中,集合的分割是无序的
# 字符或子串.join(多字符串组成的序列)
list1 = ["hello","python","i","love","you"]
t1 = ("hello","python","i","love","you")
set1 = {"hello","python","i","love","you"}

print(" ".join(list1))
print(" ".join(t1))
print(" ".join(set1))

-----------------------------
hello python i love you
hello python i love you
love i python you hello

  4、大小写转换

  • capitalize():将字符串第一个字符转换成大写。
var = "hello and python and hello world"
print(var.capitalize())    # 将字符串第一个字符转换成大写

------------------------------------
Hello and python and hello world
  • title():将字符串每个单词首字母转换成大写。
var = "hello and python and hello world"
print(var.title())    # 将字符串每个单词首字母转换成大写

-----------------------------------------
Hello And Python And Hello World
  • upper():将字符串中小写转大写。
var = "hello AND python and hello world"

print(var.upper())      # 将字符串中小写转大写

-------------------------------------------------
HELLO AND PYTHON AND HELLO WORLD
  • lower():将字符串中大写转小写。
var = "HELLO AND PYTHON AND HELLO WORLD"
print(var.lower())        #将字符串中大写转小写

------------------------------------------
hello and python and hello world
  • lstrip():删除字符串左侧空白字符。
var = "    hello AND python and hello world    "

print(var.lstrip())     
------------------------
hello AND python and hello world    .
  • rstrip():删除字符串右侧空白字符。
var = "    hello AND python and hello world    "

print(var.rstrip())   
--------------------------------------
     hello AND python and hello world
  • strip():删除字符串内的空白字符.
var = "     hello AND python and hello world    "

print(var.strip())
hello AND python and hello world

 

(三)判断

  1、startswith():检查字符串是否是以指定子串开头

var = "hello and python and hello world"

print(var.startswith("hello"))        #开头是hello,返回True
print(var.startswith("and"))        #开头是and,返回False
print(var.startswith("and",6,20))    #在索引6-20,开头是and,返回True

------------------------------------------------
True
False
True

  2、endswith():检查字符串是否是以指定子串结尾

var = "hello and python and hello world"

print(var.endswith("and"))        #结尾不是and,返回False
print(var.endswith("world"))        #结尾时world,返回True
print(var.endswith("and",0,9))    #在索引0到9,是and结尾,返回True

--------------------------------------------
False
True
True

  3、isalpha():如果字符串只包含字母则返回True 否则返回False

mystr1 = 'hello'
mystr2 = 'hello12345'

print(mystr1.isalpha())
print(mystr2.isalpha())

---------------------------------
True
False

  4、isdigit():如果字符串只包含数字则返回True,否则返回False。

mystr1 = '12345'
mystr2 = 'hello12345'

print(mystr1.isdigit())
print(mystr2.isdigit())

------------------------
True
False

  5、isalnum():如果字符串所有字符都是字母或数字则返回True,否则返回False。

mystr1 = '12345-'
mystr2 = 'hello12345'

print(mystr1.isalnum())
print(mystr2.isalnum())

-----------------------------
False
True

五、字符串运算

  • a = "Hello",b = "Python" 
+ 字符串连接 a+b 'HelloPython'
[] 通过索引获取字符串中字符 a[1] 'e'
[:] 截取字符串中的一部分 a[1:4] 'ell'
in 成员运算符,如果字符串中包含给定的字符返回True "H" in a True
not in 成员运算符,如果字符串中不包含给定的字符返回True "M" not in a True
r 取消转义 r"你\n好" 你\n好
% 格式字符串    
  • + 字符串连接
a = "hello"
b = "world"

print(a+b)

--------------------
helloworld
  • [] 通过索引获取字符串中字符
a = "hello"

print(a[1])

-----------------------
e
  • [:] 截取字符串中的一部分
a = "hello"

print(a[1:4])

-------------------
ell
  • in  成员运算符,如果字符串中包含给定的字符返回True
a = "hello"

print("h" in a)

-----------------------
True
  • not in  成员运算符,如果字符串中不包含给定的字符返回True
a = "hello"

print("h" not in a)

------------------------
False
  • r 取消转义
print("hello\nworld")
print(r"hello\nworld")

-----------------------------
hello
world
hello\nworld
  • 格式字符串
name = "张三"
age = 20
heigth = 178.5

print("我的名字是%s"%name)
print("我今年%d岁了"%age)
print("我的身高是%.2f"%heigth)

-------------------------------------------
我的名字是张三
我今年20岁了
我的身高是178.50

 

posted on 2022-09-28 14:44  乐之之  阅读(34)  评论(0编辑  收藏  举报