网络编程
位置:首页>> 网络编程>> Python编程>> Python基础之字符串常见操作经典实例详解

Python基础之字符串常见操作经典实例详解

作者:luckycyong  发布时间:2022-08-14 04:40:58 

标签:Python,字符串常见操作

本文实例讲述了Python基础之字符串常见操作。分享给大家供大家参考,具体如下:

字符串基本操作

切片

# str[beg:end]
# (下标从 0 开始)从下标为beg开始算起,切取到下标为 end-1 的元素,切取的区间为 [beg, end)
str = ' python str '
print (str[3:6])  # tho
# str[beg:end:step]
# 取 [beg, end) 之间的元素,每隔 step 个取一个
print (str[2:7:2]) # yhn
原始字符串

# 在字符串前加 r/R
# 所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符
print (r'\n')  # \n
字符串重复

# str * n, n * str
# n 为一个 int 数字
str = "hi"
print (str*2)  # hihi
print (2*str)  # hihi
in

str = ' python'
print ('p' in str)  # True
print ('py' in str)  # True
print ('py' not in str) # False

字符串常用函数

去空格

str = ' python str '
print (str)
# 去首尾空格
print (str.strip())
# 去左侧空格
print (str.lstrip())
# 去右侧空格
print (str.rstrip())
分隔字符串

str = ' 1 , 2 , 3 , 4 , 5 , '
# 默认使用空格分隔
print (str.split())  # ['1', ',', '2', ',', '3', ',', '4', ',', '5', ',']
# 指定使用空格进行分隔,首尾如果有空格,则会出现在结果中
print (str.split(' ')) # ['', '1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '']
# 指定其他字符串进行分隔
print (str.split(',')) # [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' ']
print (str.split('3 ,')) # [' 1 , 2 , ', ' 4 , 5 , ']
str = 'mississippi'
print (str.rstrip('ip'))
# 取行, python 中把 "\r","\n","\r\n",作为行分隔符
str = 'ab c\n\nde fg\rkl\r\n'
print (str.splitlines())   # ['ab c', '', 'de fg', 'kl']
print (str.splitlines(True)) # ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
拼接字符串

# str.join()方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
str = '-'
seq = ("a", "b", "c"); # 字符串序列
print (str.join(seq)) # 'a-b-c'
统计字符串里某个字符出现的次数

str = "thing example....wow!!!"
print (str.count('i', 0, 5)) # 1
print (str.count('e') ) # 2
检测字符串中是否包含子字符串

# str.find(str, beg=0, end=len(string))
# 如果包含子字符串返回开始的索引值,否则返回-1。
str1 = "this is string example....wow!!!"
str2 = "exam"
print (str1.find(str2))   # 15
print (str1.find(str2, 10)) # 15
print (str1.find(str2, 40)) # -1

# str.index(str, beg=0, end=len(string))
# 如果包含子字符串返回开始的索引值,否则抛出异常。
print (str1.index(str2))   # 15
print (str1.index(str2, 10)) # 15
print (str1.index(str2, 40))
# Traceback (most recent call last):
#  File "test.py", line 8, in
#  print str1.index(str2, 40)
#  ValueError: substring not found
# shell returned 1

# str.rfind(str, beg=0, end=len(string))
# str.rindex(str, beg=0, end=len(string))
判断字符串是否以指定前缀、后缀结尾

# str.startswith(str, beg=0,end=len(string))
# 检查字符串以指定子字符串开头,如果是则返回 True,否则返回 False
str = "this is string example....wow!!!"
print (str.startswith( 'this' ))    # True
print (str.startswith( 'is', 2, 4 ))  # True
print (str.startswith( 'this', 2, 4 )) # False

# str.endswith(suffix[, start[, end]])
# 以指定后缀结尾返回True,否则返回False
suffix = "wow!!!"
print (str.endswith(suffix))    # True
print (str.endswith(suffix,20))   # True
suffix = "is"
print (str.endswith(suffix, 2, 4))  # True
print (str.endswith(suffix, 2, 6)) # False
根据指定的分隔符将字符串进行分割

# str.partition(del)
# 返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
str = "http://www.baidu.com/"
print (str.partition("://"))  # ('http', '://', 'www.baidu.com/')
# string.rpartition(str)  从右边开始
替换字符串

# str.replace(old, new[, max])
# 字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
str = "thing example....wow!!! thisslly string";
print (str.replace("is", "was"))   # thwas was string example....wow!!! thwas was really string
print (str.replace("is", "was", 3)) # thwas was string example....wow!!! thwas is really string
# str.expandtabs(tabsize=8)
# 把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8
检测字符串组成

# 检测数字
str.isdigit()  # 检测字符串是否只由数字组成
str.isnumeric() # 检测字符串是否只由数字组成,这种方法是只针对unicode对象
str.isdecimal() # 检查字符串是否只包含十进制字符。这种方法只存在于unicode对象
# 检测字母
str.isalpha()  # 检测字符串是否只由字母组成
# 检测字母和数字
str.isalnum()  # 检测字符串是否由字母和数字组成
# 检测其他
str.isspace()  # 检测字符串是否只由空格组成
str.islower()  # 检测字符串是否由小写字母组成
str.isupper()  # 检测字符串中所有的字母是否都为大写
str.istitle()  # 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写
字符串处理

str.capitalize()  # 将字符串的第一个字母变成大写,其他字母变小写
str.lower()    # 转换字符串中所有大写字符为小写
str.upper()    # 将字符串中的小写字母转为大写字母
str.swapcase()   # 对字符串的大小写字母进行转换
max(str)  # 返回字符串 str 中最大的字母
min(str)  # 返回字符串 str 中最小的字母
len(str)  # 返回字符串的长度
str(arg) # 将 arg 转换为 string

格式化输出

居中填充

# str.center(width[, fillchar])
# 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格
str = "this is string example....wow!!!"
print (str.center(40, 'a'))  # aaaathis is string example....wow!!!aaaa
靠右填充

# str.zfill(width)
# 返回指定长度的字符串,原字符串右对齐,前面填充0
str = "this is string example....wow!!!"
print (str.zfill(40))  # 00000000this is string example....wow!!!
输出格式

print ("My name is %s and weight is %d kg!" % ('Cool', 21))
# My name is Zara and weight is 21 kg!
print ('%(language)s has %(number)03d quote types.' % {"language": "Python", "number": 2})
# Python has 002 quote types.
# str.format(*args, **kwargs)
print ('{0}, {1}, {2}'.format('a', 'b', 'c')) # a, b, c
print ('{1}, {0}, {2}'.format('a', 'b', 'c')) # b, a, c

希望本文所述对大家Python程序设计有所帮助。

来源:https://blog.csdn.net/qq_38526635/article/details/81312968

0
投稿

猜你喜欢

  • 前言文章抄袭在互联网中普遍存在,很多博主都收受其烦。近几年随着互联网的发展,抄袭等不道德行为在互联网上愈演愈烈,甚至复制、黏贴后发布标原创屡
  • 这本来是翻译Estelle Weyl的《15 JavaScript Gotchas》,里面介绍的都是在JavaScript编程实践中平时容易
  • 打过了趟深圳回来后,已经快半个月,在广州购书中心逛了下,发现2本前端书《重构HTML-改善WEB应用的设计》、《CSS3 实战》,看了一半《
  • 随着网络的普及,基于网络的应用也越来越多。网络数据库就是其中之一。通过一台或几台服务器可以为很多客户提供服务,这种方式给人们带来了很多方便,
  • 首先获取ip:<%    userip=Request.ServerVariables(&qu
  • 今天搭了个“发短信”的页面,找朋友测试,没想到一位大侠直接弄了本长篇小说发我手机上……为了我的宝贝手机能继续健康澎湃,给文本区域(texta
  • 不是炒冷饭,我添加了很多新的功能哦演示地址: xwinhtcdemo.htmCSS: global.cssHTC: xwin.htc特点:1
  •  让 PHP 支持 MySQLPHP 有专有的 MySQL 函数库以使用操作 MYSQL 数据库。在 PHP 5 及以后版本中不再
  • 我想没多少人敢保证写JavaScript能不用调试,那选择用什么方式调试会比较好呢?告别了我最爱的alert("MM")
  • string iconv ( string $in_charset , string $out_charset , string $str
  • 说到运维报警,我觉得都可以写个长篇历史来详细解释了报警的前世来生,比如最早报警都是用邮件,但邮件实时性不高,比如下班回家总不能人一直盯着邮箱
  • 前言这是个在写计算机网络课设的时候碰到的问题,卡了我一天,所以总结一下。其实在之前就有用requests写过python爬虫,但是计算机网络
  • 一段查看ASP文件源码的ASP程序,需要的朋友可以试试!<% SUB PrintLine (ByVal 
  • bbssend.asp'寻呼台页面,向在线网友发送寻呼信息<%@ Language=VBScript %&
  • 目前可实现:MD5算法、SHA256算法、先MD5后SHA256、先SHA256后MD5、两次MD5、两次SHA256、前8位MD5算法后8
  • 前言本文用Python实例阐述了一些关于进程、线程和协程的概念,由于水平有限,难免出现错漏,敬请批评改正。前提条件熟悉Python基本语法熟
  • osql 工具是一个 Microsoft Windows 32 命令提示符工具,您可以使用它运行 Transact-SQL 语句和脚本文件。
  • 名称:YUI Compressor最新版本:2.4.2用途:js/css压缩必备指数:使用难度:(YUI Compressor非常易用,只是
  • 说明:本文内容都是从Google上搜索来的,本想上http://www.alexa.com/查官方数据,访问非常慢暂且没查。使用本接口将返回
  • Oracle 背景资料 在介绍 Oracle9i 之前我们先介绍一些关于Oracle 公司的资料,让各位朋友更多了解 Oracle。 197
手机版 网络编程 asp之家 www.aspxhome.com