Python-字符串

1. 什么是字符串

  • 用 ‘’ 或 “” 包裹的信息就是字符串
  • 字符创中可以包含任意字符:如中文,字母,数字,字符

2. 字符串的定义

  • Python中,使用 str 来代表字符串类型,并且可以使用该函数定义字符串
  • 使用用 ‘’ 或 “” 直接包裹信息来定义字符串
name = str('小明')
age = '18'
message = '小明很聪明!'

3. 字符串重要思想

  • 字符串不可改变

3.1 内置函数id

  • 返回变量的内存地址
  • 数字地址 = id(变量)
name = 'xiaoming'
id(name)  #4356118459
name = 'hhhh'
id(name)  #4356118786

给变量重新赋值后,改变只是变量的地址。

3.2 内置函数len

  • 返回字符串的长度
  • 无法返回数字类型的长度,因为数字类型没有长度
  • 返回值= len(字符串)
length = len('人生苦短,我用Python')
print(length)  # 11

4. 字符串常用方法

4.1 capitalize()

  • 将字符串的首字母大写,其他字母小写

  • capitalize的用法:

newstr = string.capitalize()

注意:

  • 只对第一个字母有效
  • 只对字母有效
  • 已经是大写,则无效
name = 'xiaoming'
info = 'hello 小明'
_info = '小明 hello'
number_str = '12345'

new_name = name.capitalize()
new_info = info.capitalize()
_new_info = _info.capitalize()
new_number_str = number_str.capitalize()

print(new_name)
print(new_info)
print(_new_info)
print(new_number_str)

4.2 casefold 和 lower

  • casefold 和 lower 函数都是将字符串全体小写

用法:

newstr = string.casefold()
newstr = string.lower()

注意:

  • 只对字符串中的字母有效
  • 已经是小写,则无效
  • lower只能将英语字母小写,casefold可以将更多语种小写
message_en = 'How do you do? Xiaoming'
message_ch = '你好啊,Xiaoming'
message_mix = '你好啊,Xiaoming,今天是星期3'

message_en_lower = message_en.lower()
message_en_casefold = message_en.casefold()

message_ch_lower = message_ch.lower()
message_ch_casefold = message_ch.casefold()

message_mix_lower = message_mix.lower()
message_mix_casefold = message_mix.casefold()

print(message_en_lower, message_en_casefold)
print(message_ch_lower, message_ch_casefold)
print(message_mix_lower, message_mix_casefold)

4.3 upper()

  • 将字符串全体大写

用法:

big_str = string.upper()

注意:

  • 只对字符串中的字符有效
  • 已经是大写,则无效
info = 'Hello World! Hello Xiaoming'
big_str = info.upper()
small_info = info.lower()

print(big_str)
print(small_info)

4.4 swapcase()

  • 将字符串中大小写字母进行转换

用法:

new_str = string.swapcase()

注意:

  • 只对字符串中的字母有效
info_one = 'Python Code Is Good'
info_two = 'PYTHON DJANGO FLASK'
info_three = 'python web so easy'

info_one_new = info_one.swapcase()
info_two_new = info_two.swapcase()
info_three_new = info_three.swapcase()

print(info_one_new)
print(info_two_new)
print(info_three_new)

4.5 zfill()

为字符串定义长度,如不满足,缺少部分用0补齐

用法:

new_str = string.zfill(width)
# width:新字符串希望的长度

注意:

  • 与字符串的字符无关
  • 如果定义长度小于当前字符串长度,则不发生变化
heart = 'love'

if __name__ == '__main__':
    print(' t  ' + heart)
    print('t   ' + heart)
    print('     ' + heart)
    print(heart.zfill(10))
    print(heart.zfill(9))
    print(heart.zfill(8))
    print(heart.zfill(6))
    print(heart.zfill(4))

4.6 count()

  • 返回当前字符串中某个成员(元素)的个数

用法:

inttype = string.count(item)
# item:查询个数的元素

注意:

  • 如果查询的成员(元素)不存在,则返回0
info = """Welcome! Are you completely new to programming? If not then we presume you will be looking for information 
about why and how to get started with Python. Fortunately an experienced programmer in any programming language (
whatever it may be) can pick up Python very quickly. It's also easy for beginners to use and learn, so jump in! """

a = info.count('a')
b = info.count('b')
c = info.count('c')
d = info.count('d')
e = info.count('e')
f = info.count('f')

print(a, b, c, d, e, f)

number_list = [a, b, c, d, e, f]
print(number_list)
print('在列表中最大的数值:', max(number_list))

number_dict = {
    'a': a,
    'b': b,
    'c': c,
    'd': d,
    'e': e,
    'f': f
}
print('每个成员对应的数值分别是:', number_dict)

4.7 startswith 和 endswith

  • startswith判断字符串开始位是否是某成员(元素)
  • endswith判断字符串结尾是否是某成员(元素)

用法:

string.startswith(item)
string.endswith(item)
# item:你想查询匹配的元素,返回一个布尔值
info = 'this is a string example!!'

result = info.startswith('this')
print(result)
result = info.startswith('this is a string example!!')
print(result)

result = info.endswith('!!')
print('result:', result)

result = info.endswith('this is a string example!!')
print('result:', result)

4.8 find 和 index

  • find 和 index 都是返回你想寻找的成员的位置

用法:

string.find(item)
	# item:你想要查询的元素,返回一个整型
strin.index(item)
	# item:你想要查询的元素,返回一个整型或者报错

区别:

  • 如果find找不到元素,会返回-1
  • 如果index找不到元素,会导致程序报错
info = 'python is a good code'

result = info.find('a')
print(result)
result = info.find('ok')

result = info.index('a')
print(result)
result = info.index('ok')
print(result)

4.9 strip()

  • strip将去掉字符串左右两边的指定元素,默认值空格

用法:

new_str = string.strip(item)
# item: 填写你想去掉的元素,可不填写

拓展:

  • 传入的元素如果不在开头或结尾则无效

  • lstrip 仅去掉字符串开头的指定元素或空格

  • rstrip 仅去掉字符串结尾的指定元素或空格

info = ' my name is xiaoming '
new_info = info.strip()
print('.' + new_info + '.')

new_info_01 = info.strip(info)
print(new_info_01)
print(len(new_info_01))

new_str = 'abcde'
print(new_str.lstrip('a'))
print(new_str.rsplit('e'))

4.10 replace()

  • 将字符串中的旧元素替换成新元素,并能指定替换的数量

用法:

newstr = string.replace(old, new, max)
"""
	old:被替换的元素
	new:提花old的新元素
	max:可选,代表替换几个,默认全部替换全部匹配的old元素
"""
info = """欢迎!您对编程完全陌生吗?如果不是,那么我们假设您将寻找有关为什么以及如何开始使用 Python 的信息。幸运的是,任何编程语言(无论它是什么)的有经验的程序员都可以非常快速地掌握 
Python。初学者也很容易使用和学习,所以 赶快加入吧! """

a = '编程'
b = 'Python'
c = '初学者'
d = '*'
e = '0'
f = '#'

test = info.replace(a, d).replace(b, e).replace(c, f)
print(test)

# test = info.replace(a, d)
# print(test)
# test = info.replace(b, e)
# print(test)
# test = info.replace(c, f)
# print(test)

4.11 字符串bool集合

字符串中返回bool类型的函数集合

4.11.1 isspace()

功能:

isspace 判断字符串是否是一个由空格组成的字符串

用法:

booltype = string.isspace()
# 无参可传,返回一个布尔类型

4.11.2 istitle()

功能:

istitile 判断字符串是否是一个标题类型

用法:

booltype = String.istitle()
# 无参可传,返回一个布尔类型

4.11.3 isupper 和 islower

isupper 判断字符串中的字母是否都是大写

islower 判断字符串中的字符是否都是小写

用法:

booltype = string.isupper()
booltype = string.islower()
# 无参可传,返回一个布尔类型
title = 'Back If China'
upper_str = 'PYTHON IS A GOOD CODE 哈哈'
upper_str_02 = 'Python Is A Good Code'
lower_str = 'i love python 哈哈 !'
not_empty = '!     !'

print(title.istitle())
print(upper_str_02.istitle())
print('isupper', upper_str.isupper())
print('islower', lower_str.islower())
print(not_empty.isspace())

4.12 字符串编码格式

常见编码格式:

  • GBK 中文编码
  • ASCII 英文编码
  • utf-8 是一种国际通用的编码格式
# coding:ascii

name = '小明'
print(name)
age = 10
heart = 'love'
print(age, heart)

# SyntaxError: encoding problem: ascii

4.13 字符串格式化符号

  • 用于对应各种数据类型的格式化符号
符号说明
%s格式化字符串,通用类型
%d格式化整型
%f格式化浮点型
%u格式化无符号整型
%c格式化字符
%o格式化无符号八进制数
%x格式化无符号16进制数
%e科学计数法格式化浮点数
print('%c' % 1020)
# print('%c' % 'ba')
print('%c' % 999999)

print('%u' % -1)
print('%f' % 1.2)
print('%f' % 3014)
print('%f' % 12)

print('%d' % -10)
print('%d' % 1.2)

print('%s' % '123')
print('%s' % 123)

# print('{:d}'.format(1))
# print('{:f}'.format(1.2))
# print('{:s}'.format(12))

print('%o' % 24)
print('%x' % 32)
number = int('123abc', 16)
print(number)
print('%x' % number)

print('%e' % 1.2)

4.14 字符串特殊字符

4.14.1 转义字符

  • 字符要转成其他含义的功能,所以我们叫它转义字符
  • \ + 字符
符号说明
\n换行,一般用于末尾,strip对其也有效
\t横向制表符(可以认为是个间隔符)
\v纵向指标符(会有一个男性符号)
\a响铃
\b退格符,将光标前移,覆盖(删掉前一个)
\r回车
\f翻页(几乎用不到,会出现一个女性符号)
\’转义字符串中的单引号
\"转义字符串中的双引号
\\转义斜杠
info_n = ('my name \nis %s\n' % 'xiaoming')
print(info_n)

info_t = 'my name \tis xiaoming'
print(info_t)

info_v = 'my name \vis xiaoming'
print(info_v)

info_a = 'my name \ais xiaoming'
print(info_a)

info_b = 'my name is xiaoming\b'
print(info_b)

info_r = 'my name is xiaoming\r'
print(1, info_r, info_b)

info_f = 'my name is xiaoming\f'
print('f', info_f)

print('my name is \'xiaoming\'')

print('my name is \"xiaoming\"')

print('my name is \\xiaoming')

4.14.2 转义无效符

  • 在Python中,在字符串前加 r 来讲字符串的转义字符无效化
print(r'my name is \\xiaoming\n')
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值