【Python】基本数据类型--字符串

一、定义

单行字符串:使用 '…' 或者 "…"

多行字符串:使用 '''…'''

"字符串"
'字符串'

'''
多行字符
多行字符
'''

二、常用特殊字符

\:转义符。\n:换行

r:忽略转义符的作用。用在字符串开头,内部"\"不再起转义符作用。

+:多个字符串连接。

print('a\nb')         # a
                      # b
print(r'a\nb')        # a\nb

print('ab' + 'cd')    # abcd

三、字面量插值

字面量:以变量或常量给出的原始值,在程序中可以直接使用字面量。

字面量插值:将变量与常量以及表达式插入的一种技术,可以避免字符串拼接问题。

1、格式化输出

写法:"%x"  %  (x)

  • %c 格式化字符及其ASCII码
  • %s 格式化字符串
  • %d 格式化整数
  • %u 格式化无符号整型
  • %o 格式化无符号八进制数
  • %x 格式化无符号十六进制数
  • %X 格式化无符号十六进制数(大写)
  • %f  格式化浮点数字,可指定小数点后的精度
  • %e 用科学计数法格式化浮点数
  • %p 用十六进制数格式化变量的地址
print('小明第%d次考试,考了%.2f,等级%s' % (2, 92.5, 'A'))
# 输出:小明第2次考试,考了92.50,等级A
# %.2f:代表保留两位小数

2、format()

写法:"{}".format(x)

# 不指定位置,按默认顺序
print("{} name is {}".format("My", "Andy"))
# 指定位置
print("{1} name is {0}".format("Andy", "My"))
# 通过名称传递变量
print("{} name is {name}".format("My", name = "Andy"))

# 均是输出:My name is Andy

3、f

写法:f"{变量}"

name = "Andy"
print(f"My name is {name}")    # 输出:My name is Andy

四、常用API 

1、join()

将列表转化为字符串

写法:" ".join(list)," "内的字符表示以这个字符连接。

a = ["My", "name", "is", "Andy"]
print(' '.join(a))    # 输出:My name is Andy
print('|'.join(a))    # 输出:My|name|is|Andy

2、split()

数据切分操作

写法:str.split(" ")。" "内的字符表示以这个字符切分。

s = "My name is Andy"
print(s.split(" "))    # 输出:['My', 'name', 'is', 'Andy']
print(s.split("a"))    # 输出:['My n', 'me is Andy']

3、replace()

替换目标字符串

写法:str.replace(" ",  " ")。前一个""是被替换的字符串,后一个""是替换的字符串。

s = "My name is Andy"
print(s.replace("Andy", "Kim"))    # 输出:My name is Kim

4、strip() 

去掉字符串首尾空格

写法:str.strip()。

s = " My name is Andy "
print(s.strip())    # 输出:My name is Andy

lstrip():去掉头部空格,left缩写;rstrip():去掉尾部空格,right缩写

s = " My name is Andy "
print(s.lstrip())    # 输出:My name is Andy
print(s.rstrip())    # 输出: My name is Andy

 5、find()

查找在字符串里第一个出现的子串的位置,返回索引。

写法:str.find(" ")。" "内写需要查找的子串。未找到时返回-1。

s = "My name is Andy"
print(s.find("am"))    # 输出:4
print(s.find("aw"))    # 输出:-1

6、upper()、lower()、title()、capitalize()

  • upper():把字符串中所有的字母转换成大写字母
  • lower():把字符串中所有的字母转换成小写字母
  • title():把字符串中每个单词的首字母转化为大写,其余小写 
  • capitalize():把字符串的首字母转化为大写字母,其余小写

写法: str.upper()、str.lower()、str.title()、str.capitalize()

s = "My name is Andy"
print(s.upper())        # 输出:MY NAME IS ANDY
print(s.lower())        # 输出:my name is andy
print(s.title())        # 输出:My Name Is Andy
print(s.capitalize())   # 输出:My name is andy

猜你喜欢

转载自blog.csdn.net/Yocczy/article/details/131819255