[转载] python 字符串包含某个字符_python字符串

参考链接: Python字符串capitalize()

str字符串

 本节内容概览

   1、何为str?2、转义字符3、字符串格式化4、Python字符串内建函数和操作5、python字符串练习

 一、字符串

 Python中最常用的数据类型用来表示文字信息在Python中用单引号、双引号、三引号括起来的

 

  # 单引号示例

s = 'I am jason'

print(s)

I am jason

# 三引号示例

s = '''

I

am

jason

'''

print(s)

I

am

jason

 

 二、转义字符

 用一个特殊的方法表示出一系列不方便写出的内容,比如回车键、换行符、退格符(需要在字符中使用特殊字符时)借助反斜杠字符,一旦字符串中出现反斜杠,则反斜杠后面一个或者几个字符表示已经不是原来的意思了,进行了转义在字符串中,一旦出现反斜杠就要加倍小心,可能有转义字符出现 不同系统对换行操作有不同的表示,例如

   windows: nlinux: rn 常用的转义字符

    # 在python里,单个反斜杠表示此行未结束,处于美观,需要下一行继续 (在行尾时)续行符 # 反斜杠符号n # 换行t # 横向制表符f # 换页 

 

  # 转义字符案例1

# 想表达Let's Go

# 使用转义字符

s = 'Let's Go'

print(s)

 

# 使用单双引号嵌套

s = "Let's Go"

print(s)

 

# 表示斜杆

# 想表示c:User

s = "c:User"

print(s)

 

# 回车换行

# 想表达的效果是:

# I

# am

# jason

 

s = "Inamnjason"

print(s)

Let's Go

Let's Go

c:User

I

am

jason

# 单个斜杠案例1

 

def myDemo(x, 

           y, 

           z):

    print("hhh")

 

myDemo(1, 2, 3)

hhh

 

 三、字符串格式化

 把字符串按照一定格式进行打印或者填充格式化的分类:

   传统格式化

     使用%进行格式化(%也叫占位符)占位符可以单独使用占位符一般只能被同类型替换,或者替换类型能被转换成占位符的类型需要格式化的信息大于一个,则用括号括起来 常见的占位符有: %d 整数 %f 浮点数 %s 字符串 %x 十六进制整数format

     使用函数形式进行格式化,代替前面的百分号 

 

  # %格式化练习1

 

s = "I am %s"

print(s)

 

print(s% "jason")

 

print("I am %s" % "liu")

I am %s

I am jason

I am tony9

I am liu

# %格式化练习1(多个格式化)

 

s = "jason is %d old"

print(s%19)

 

s = "jason is %.2fm heigh, %.2fkg weight"

print(s%(10.0, 10.0))

jason is 19 old

jason is 10.00m heigh, 10.000000kg weight

# format格式化练习 

 

# 不用指定位置,按顺序读取

# 案例1

s = "{} {}!"

print(s.format("hello", "world"))

 

# 案例2

s = "{} {}!".format("hello", 1)

print(s)

 

# 设置指定位置

# 案例3

s = "{1} {0}!".format("hello", "world")

print(s)

 

# 使用命名参数

# 案例4

s = "我们的是{school_name}, 网址是{url}, {teacher}"

s = s.format(school_name="test", url="test", teacher="test")

print(s)

 

# 使用命名参数

# 案例5

# 通过字典设置参数,但是需要解包

s = "我们的是{school_name}, 网址是{url}, {teacher}"

s_dict = {"school_name":"test", "url":"test", "teacher":"test"}

print(s.format(**s_dict))

 

# 对数字的格式化需要用到

s = "jason is {:.2f}m heigh, {:.2f}kg weight"

print(s.format(1.84, 65))

hello world!

hello 1!

world hello!

我们的是test, 网址是test, test

我们的是test, 网址是test, test

jason is 1.84m heigh, 65.00kg weight

 

 四、str内建函数和操作

 很多语言字符串使用string表示,但python中使用str表示字符串字符串查找类,in, find, index, rfind字符串判断类,islower, isupper, startswith字符串内容判断,startswith/endswith字符串操作类:空格剥离(strip), 字符串拆分(split), 合成字符串(join), 大小写转换(upper), 子字符串替换(replace), 组合多个列表(zip)字符串连接,+, *, 字符串可当作列表

 

  help(str.__add__)

Help on wrapper_descriptor:

 

__add__(self, value, /)

    Return self+value.

 

 4.1、字符串查找

 in:包含find: 查找字符串中是否包含一个子串,并返回子串所在的位置 (Return -1 on failure.)rfind: 从从右查找index: 查找字符串中是否包含一个子串,并返回子串所在的位置(Raises ValueError when the substring is not found)

 

  s = "I am jasonliu and jasonzhang"

s1 = "jason"

print(s.find(s1))

 

s2 = "tony"

print(s.find(s2))

 

s3 = "and"

print(s.find(s3, 17))

 

s4 = "jason"

print(s.rfind(s4))

5

-1

-1

18

s = "I am jasonliu and jasonzhang"

s1 = "jason"

print(s.index(s1))

 

s2 = "tony"

print(s.index(s2))

5

 

 

 

---------------------------------------------------------------------------

 

ValueError                                Traceback (most recent call last)

 

<ipython-input-69-1b293ca51502> in <module>

      4 

      5 s2 = "tony"

----> 6 print(s.index(s2))

 

 

ValueError: substring not found

 

 4.2、字符串判断

 此类函数的特点一般都是用is开头islower: 判断字符串是否都是小写字母,是则返回True,否则返回Falseisupper: 判断字符串是否都是大写字母,是则返回True,否则返回Falseistitle: 判断每个单词开头字母是否是大写isspace: 判断字符串是否是空字符串isalpha: 判断是否是字母

   此函数默认的前提是字符串至少包含一个字符,如果没有,统一返回False汉字被认为是alpha,所以,次函数不能作为区分英文字母还是汉字的标识,区分中英文请使用unicode码主要是有区别,防止被坑isdigit, isnumeric, isdecimal 三个判断数字的函数

   此类函数不建议使用,在后期爬虫中,判断是否是数字建议采用正则表达式 digit: True: unicode数字,byte数字,全角数字,罗马数字 False: 罗马数字 Error: byte数字isalnum: 检查字符串是否由字母加数字组成

 

  s = "jason"

print(s.islower())

 

s = "Jason"

print(s.islower())

 

s1 = "test is test"

print(s1.isalpha())

True

False

False

chin_num = "一二三四"

print(chin_num.isdigit())

print(chin_num.isnumeric())

print(chin_num.isdecimal())

False

True

False

 

 4.3、内容判断类

 startswith/endswith:是否以xxx开头或结尾

   检测某个字符串是否以某个子串开头,常用三个参数suffix:被检查的字符串,必须有start:检查范围的开始范围end:检查范围的结束范围

 

  test1= "Jason Liu"

test2 = "Tony Liu"

 

s = "Jason Liu and Tony Liu"

print(s.startswith(test1, 5))

print(s.endswith(test2))

False

True

 

 4.4、操作类

 strip: 删除字符串两边的空格(默认,也可以指定需要删除的东西),

   lstrip/rstripsplit:字符串拆分splitlines:已换行符拆分join:合成字符串upper:将所有字母变成大写lower:将所有字母变为小写swapcase:大小写互换replace:子字符串替换zip:组合多个列表capitalize:首字母大写title:每个单词首字母大写len:计算字符串长度count:计算字符串出现次数,返回整形

 

  c = "JJJason and tony "

print(c.strip(), end='---')

print()

print(c.strip('J'))

JJJason and tony---

ason and tony

c = "jason and tony "

print(c.split(sep=" "))

['jason', 'and', 'tony', '']

s1 = "$"

s2 = "-"

s3 = " "

ss = ["Jason liu", "Tony liu"]

print(s1.join(ss))

 

print(" ".join(ss))

Jason liu$Tony liu

Jason liu Tony liu

c = "jason and tony "

print(c.upper())

JASON AND TONY

c = "jason and tony"

print(c.replace("tony", "a"))

jason and a

c = ["jason", "liu", "tony"]

d = ["dana", "yd"]

 

for x, y in zip(c, d):

    print(x, y)

jason dana

liu yd

 

 4.5 字符串连接

 +*

 

  c = "jason and tony"

d = " liu"

print(c+d)

 

print(d*3)

jason and tony liu

 liu liu liu

 

 4.6 字符串当列表

 

  s = "jason and tony"

print(s[0])

 

print(id(s))

print(id(s[:]))

print(id(s[0:2]))

j

4406693552

4406693552

4406709920

 

 五、字符串练习

 

  # "Tuling"和"tuling" 是一样的吗?

"Tuling" == "tuling"

False

# 字符串拼接

str = "I love" + "yuandan"

print(str)

I loveyuandan

# 编写程序,要求用户输入姓名并且打印"你好,姓名”

 

name = input("请输入姓名:")

print("你好"+name)

请输入姓名:jason

你好jason

# 编写程序,要求用户输入1-100之间的整数并且判断,输入符合要求的打印"你好看”,否则打印“你丑八怪”

 

temp = input("请输入一个零到一百的整数:")

if temp.isdigit():

    temp = int(temp)

    if 1 <= temp <= 100:

        print("你好看")

    else:

        print("你丑八怪")

else:

    print("你丑八怪")

请输入一个零到一百的整数:1

你好看