python 字符串的操作详解

字符串的基本使用:

# -*- coding:utf-8 -*-
# 一段普通的文本就是一个字符串
# python里字符串的表示方式:

# 双引号、单引号、三个双引号、三个单引号、 反引号(废弃)
a = 'hello world'
b = "hello world"
# c = 'xiaoming said I'm xiaoming'
c = "xiaoming said I'm xiaoming"
print(c)

d = 'xiaoming said "I am xiaoming"'
print(d)

# 三个单引号或者三个双引号,可以让字符串里的引号原样输出
e = '''xiaoming said "I'm xiaoming"'''
print(e)
f = '''xiaoming said "I'm xiaoming"'''
print(f)

# \ 是转义字符,用来对 \ 紧跟的字符进行转义
# \\ 显示一个 \
g = 'xiaoming said "I\'m xiaoming"'
print(g)

print('hello \nworld')
print('hello\tworld')
print('hello \\n world')
# r''  ==> 字符串里的转义字符原样输出
print(r'hello \t world')

x = 'good'
a = `x`
print(a)

字符串的长度与下标:

a = 'hello world'

# len内置函数,可以获取到字符串的长度
print(len(a))

print(len(['hello', 'hi', 'good']))
print(len(('hello', 'hi', 'good')))
print(len({'name': 'zhangsan', 'age': 18}))
print(len(range(5, 19)))

# 可以使用下标获取到指定的数据。注意:下标是从0开始的!
print(a[4])

# i = 0
# while i < len(a):
#     print(a[i])
#     i += 1

for x in a:
    print(x)

字符串的切片:

chars = 'abcefghijklmnopqrst'

# 切片作用:从字符串里获取一部分数据
# 语法: chars[start:stop:step] 包含开始,不包含结束
print(chars[5])  # 获取到第5个字符
print(chars[3:])  # 从第三个字符开始,截取到最后
print(chars[2:10])  # 从第2个字符(包含第2个)开始,截取到第10个(不包含第10个)
print(chars[2:10:3])  # 从第2个字符开始,每隔两个字符,截取一个,一直截取到第10(不包含)
# 如果不设置步长,默认是1,连着截取,不间隔;步长不能为0
# print(chars[2:10:0])   报错,步长不能为0
# 步长如果为负数,表示从右往左截取。
print(chars[10:2:-1])  # 从第10个开始(包含)往左截取到第2个(不包含第2个)
print(chars[-10:-2])  # 从倒数第10个(包含)开始,从左往右,截取到第倒数第2个(不包含)
print(chars[:3])  # 从头开始,截取到第3个(不包含)
print(chars[::])  # 从头到尾截取
print(chars[::-1])  # 翻转字符串

print(chars)  # 原有的字符串没有发生任何的变化

字符串的常见方法:

len是内置函数。len(‘hello’) 是把 ‘hello’ 字符串当做参数传递给 len 内置函数

# len('hello')

# 面向对象的语法。  把'hello'当做一个对象,调用这个对象的 count 方法
# count 方法返回元素出现次数,如果没有该元素  返回 0
# print('hello'.count('l'))

# 字符串的方法:
# 查找内容:find,index,rfind,rindex
# print('hello'.find('e'))  # 用来查找指定字符第一次出现的位置下标
# print('hello'.find('z'))  # 如果查找的字符在字符串里不存在,会返回 -1

# print('hello world'.rfind('m'))  # rfind查找指定支付最后一次出现的位置,如果不存在返回 -1

# index 和find的使用基本一致; rindex 和 rfind的使用也基本一致
# 区别在于:使用find方法,如果查找的字符不存在,会返回-1;
# 使用index方法,如果查找的字符不存在,会报错
# print('hello'.index('e'))
# try:
    # print('hello'.index('z'))  # 查找的字符不存在,会报错
# except ValueError:
#     print('error')

# 判断:startswith,endswith,isalpha,isdigit,isalnum,isspace
# print('hello'.startswith('h'))  # True  判断字符串是否以指定的字符开始
# print('hello world'.endswith('o'))

# isalpha判断是否是字母
# print('abc'.isalpha())  # True
# print('123'.isalpha())  # False

# 判断是否是数字
# print('abc'.isdigit())
# print('1234'.isdigit())

 # 检测字符串是否只由数字组成。这种方法是只针对unicode对象
# print('Ⅷ'.isnumeric())

# 计算出现次数:count
# 替换内容:replace
# 切割字符串:split,rsplit,splitlines,partition,rpartition
# 修改大小写:capitalize,title,upper,lower
# 空格处理:ljust,rjust,center,lstrip,rstrip,strip
# 字符串拼接:join


# isalnum 判断是否由数字和字母组成
# print('abc'.isalnum())
# print('12345'.isalnum())
# print('a1b2c3d4e5'.isalnum())

# isspace 判断是否只有空格
# print('hello world'.isspace())  # False
# print('    '.isspace())  # True

# 计算出现次数:count
# print('hello world'.count('l'))  # 3
# 指定位置开始结束
# print('hello world'.count('l', 2, 7))  # 2

# 替换内容:replace
# b = 'good morning'
# x = b.replace('o', 'x')
# print(x)  # gxxd mxrning 执行方法以后得到的结果变了
# print(b)  # good morning 原有的字符串没有发生变化

# 指定修改的次数
# y = b.replace('o', 'x', 2)
# print(y)

# 修改大小写:capitalize,title,upper,lower
# print('hello.hi.yes\ngood'.capitalize())
# print('hello hi yes'.title())
# print('yes'.upper())  # YES
# print('GooD'.lower())  # good

# x = input('是否退出?yes/no')
# if x.lower() == 'yes':
# if x.upper() == 'YES':
#     print('用户确定退出')

# 空格处理:ljust,rjust,center,lstrip,rstrip,strip
# print('hello'.ljust(10))  # 如果长度不够10,在右边补空格
# print('hello'.ljust(10, '+'))
#
# print('hello'.rjust(10))
# print('hello'.rjust(10, '-'))
# print('hello'.center(10, '*'))

# print('       hello         '.lstrip())
# print('       hello         '.rstrip())
# print('       hello         '.strip())

# print('hello         '.lstrip('h'))

# username = input('请输入您的用户名:')
# if username.strip() == '':
# if len(username.strip()) == 0:
# if not username.strip():
#     print('对不起,用户名不能为空')

# 切割字符串:split,rsplit,splitlines,partition,rpartition

# split 使用指定的字符对字符串进行分割,得到一个列表
# print('hello,hi,good,yes,no'.split(','))
# print('hello-hi-good-yes-no'.split('-', 2))
#
# print('hello_hi_good_yes_no'.rsplit('_'))
# print('hello_hi_good_yes_no'.rsplit('_', 2))
#
# print('2019-08-23.txt'.split('.')[0])
# print('2019.08.23.log.txt'.rsplit('.', 1))
#
print('hello\nhi\ngood\nyes\n'.split('\n'))
print('hello\nhi\ngood\nyes\n'.splitlines())

print('abcodefoghijkomndp'.partition('o'))
print('abcodefoghijkomndp'.rpartition('o'))

# 字符串拼接:join
# print('hello,hi,good,yes,no'.split(','))  # ['hello', 'hi', 'good', 'yes', 'no']
#
print(''.join(['ab', 'c', 'e']))
print('*'.join(['hello', 'hi', 'good', 'yes', 'no']))  # hello*hi*good*yes*no

# for x in ['hello', 'hi', 'good', 'yes', 'no']:
#     print(x)

# for x in 'abcdef':
#     print(x)
# print('+'.join('abcdef'))  # a+b+c+d+e+f
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的字符串是不可变的序列,可以包含任意字符,包括字母、数字、符号等。下面是一些关于Python字符串详解: 1. 字符串的创建:可以使用单引号、双引号或三引号来创建字符串。例如:'hello'、"world"、'''Python'''。 2. 字符串的访问:可以通过索引和切片来访问字符串中的字符或子字符串。索引从0开始,可以使用负数索引从末尾开始计数。例如:s = 'hello',s[0]是'h',s[-1]是'o',s[1:4]是'ell'。 3. 字符串的拼接:使用加号(+)来拼接字符串。例如:s1 = 'hello',s2 = 'world',s3 = s1 + s2,s3的值为'helloworld'。 4. 字符串的常用方法: - len():返回字符串的长度。 - lower():将字符串转换为小写。 - upper():将字符串转换为大写。 - strip():去除字符串两端的空格或指定字符。 - split():将字符串按指定分隔符分割成列表。 - join():将列表中的字符串元素按指定分隔符拼接成一个字符串。 - replace():替换字符串中的指定子串。 - find():查找子串在字符串中的位置。 5. 字符串的格式化:使用格式化操作符(%)或format()方法来格式化字符串。例如:name = 'Alice',age = 25,s = 'My name is %s, and I am %d years old.' % (name, age)。 6. 字符串的常用操作: - 字符串的比较:使用比较运算符(==、!=、<、>、<=、>=)来比较字符串的大小。 - 字符串的遍历:可以使用for循环遍历字符串中的每个字符。 - 字符串的判断:可以使用isalpha()、isdigit()、isalnum()等方法判断字符串的类型。 这些只是Python字符串的一些基本特性和操作,还有更多高级用法和方法可以进一步探索和学习。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值