跳至主要内容

python 之 Strings (字符串)


https://www.programiz.com/python-programming/string

Python不支持字符类型,它们被视为长度为1的字符串,也被视为子字符串

字符串是一系列字符。它可以通过使用双引号在python中声明。字符串是不可变的,它表明,一旦将String绑定到变量,它能被删除,但不能被修改

通过在引号中放置一系列字符来创建字符串。字符串可以用单引号,双引号或三引号括起来,它们由三个单引号或三个双引号组成

三引号中的字符串可以跨越多行而不使用转义字符

默认情况下,Python 2中的字符串是非Unicode(ASCII),但也支持Unicode。
另一方面,Python 3字符串都是Unicode(UTF-8)
Strings in Python 2.
>>> print(type('Python String'))
<type 'str'>
>>> print(type(u'Python Unicode String'))
<type 'unicode'>
Strings in Python 3.
>>> print(type('Python String'))
<class 'str'>
>>> print(type(u'Python Unicode String'))
<class 'str'>

Python中的字符串运算符


字符串索引
查看字母x在字符串中的索引位置
string.index('x')

字符串切片Slicing [ ]  Range Slicing [X:y]
使用方括号与索引或索引范围一起切​​片以获得子串
string = "python"
print(string[4])
slice运算符在给定索引处打印字符
print(string[2:4])
打印给定范围内的字符
print(string[::-1])

字符串串联Concatenation (+)
string1+string2
将两个字符串合并为一个


字符串重复Repetition (*)
string*9
通过重复给定次数来创建新字符串,它实质上是一个多重串联
>>> ".-." * 4
'.-..-..-..-.'


成员资格Membership( in,not in)

检查字符串中是否存在某些字符,返回true,false
string="Long" 
print("Lo" in string)  
#True

print("Ln" in string)
#False

print("Ln" not in string)
#False

迭代Iterating (For)
使用此运算符,我们可以遍历字符串的所有字符
# example
for var in var1:print (var, end ="")
原始字符串Raw String (r/R)

# example
print (r'\n')
# \n
print (R'\n')
# \n

Python中的内置字符串函数


字符串替换  replace(old,new[,count])
var='This is a good example'
str='was'
print (var.replace('is',str))
# Thwas was a good example
print (var.replace('is',str,1))
# Thwas is a good example
string.replace('旧','新')
oldstring = 'I like You!'
newstring = oldstring.replace('like', 'love')
print(newstring)


字符串大写
string.upper()
var = 'TechBeamers'
print (var.upper())
# TECHBEAMERS

字符串小写
string.lower()
var = 'TechBeamers'
print (var.lower())
# techbeamers

字符串首字母大写
string.capitalize()
返回首个单词大写字母,其余小写字母的字符串

var = 'welcome to Python programming'
print (var.capitalize())
# Welcome to python programming

string.title()
所有单词均以大写字母开头,单词中的其余字符均以小写字母开头
var = 'welcome to Python programming'
print (var.title())
# Welcome To Python Programming


字符串大小写互换
string.swapcase()
var = 'TechBeamers'
print (var.swapcase())
# tECHbEAMERS

字符串计数count( str[, beg [, end]])
如果给出了beg和end索引,则返回子字符串'str'在[beg,end]范围内出现的次数,否则搜索将以完整字符串继续进行,字符串搜索区分大小写


var='TechBeamers'
str='e'
print (var.count(str))
# 3

var1='Eagle Eyes'
print (var1.count('e'))
# 2

var2='Eagle Eyes'
print (var2.count('E',0,5))
# 1

rjust(width[,fillchar])
返回String的填充版本,其中原始String左对齐到width列的总和 默认情况下,填充使用空格。否则,“ fillchar”指定填充字符。

var='Python'
print (var.rjust(10))
#    Python

print (var.rjust(10,'-'))
# ----Python

ljust(width[,fillchar])返回String的填充版本,其中原始String左对齐到width列的总和 默认情况下,填充使用空格。否则,“ fillchar”指定填充字符


var='Python'
print (var.ljust(10))
# Python      

print (var.ljust(10,'-'))
# Python----

center(width[,fillchar])在将原始内容推入中心的同时返回填充有输入字符的字符串。 默认情况下,填充使用空格。否则,“ fillchar”指定填充字符。

var='Python'
print (var.center(20))
#      Python

print (var.center(20,'*'))
# *******Python*******

zfill(width)返回填充有原始内容的字符串,该内容在左侧用零填充,以使String的总长度等于输入大小
如果字符串中存在前导符号(+/-),则使用此功能将在符号之后而不是符号之前开始填充

var='Python'
print (var.zfill(10))
# 0000Python

var='+Python'
print (var.zfill(10))
# +000Python


find(str [,i [,j]])在完整的字符串中搜索"str''。如果找到"str'',则此函数返回索引,否则返回"-1'' 
i = search从此索引开始,j = search从此索引结束


var="Tech Beamers"
str="Beam"
print (var.find(str))
# 5

var="Tech Beamers"
str="Beam"
print (var.find(str,4))
# 5

var="Tech Beamers"
str="Beam"
print (var.find(str,7))
# -1
index(str[,i [,j]])与“find”方法相同。唯一的区别是,如果不存在“ str”,它将引发“ ValueError”异常


var='Tech Beamers'
str='Beam'
print (var.index(str))
# 5

var='Tech Beamers'
str='Beam'
print (var.index(str,4))
# 5

var='Tech Beamers'
str='Beam'
print (var.index(str,7))
# ValueError: substring not found
rfind(str[,i [,j]])这与find()相同,只是此函数返回找到“str”的最后一个索引。如果未找到“str”,则返回“-1”

var='This is a good example'
str='is'
print (var.rfind(str,0,10))
# 5

print (var.rfind(str,10))
# -1

count(str[,i [,j]])返回字符串中子字符串“ str”的出现次数
i = search从此索引开始,j = search从此索引结束

var='This is a good example'
str='is'
print (var.count(str))
# 2

print (var.count(str,4,10))
# 1

反转字符串
string="123456"
string[::-1]
或者"".join(reversed(string))


拆分字符串split([sep[,maxsplit]]) 
返回用“ sep”作为分隔符分割字符串后获得的子字符串列表
其中sep =分隔符,默认为空格,maxsplit =要进行的分割数

var = "This is a good example"
print (var.split())
# ['This', 'is', 'a', 'good', 'example']
print (var.split(' ', 3))
# ['This', 'is', 'a', 'good example']
word = "I love You!"
word.split(" ")
分隔符是空格,则返回['I', 'love', 'You!']

word.split("o")
分隔符是o,怎返回['I l', 've Y', 'u!']


join(seq)
返回在将序列“ seq”与定界符字符串连接后获得的字符串。
seq=('ab','bc','cd')
str='='
print (str.join(seq))
# ab=bc=cd

splitlines(num)
在换行符处拆分字符串,并在删除换行符后返回列表
其中,num =如果这是一个正值。它指示换行符将出现在返回的列表中
var='Print new line\nNextline\n\nMove again to new line'
print (var.splitlines())
# ['Print new line', 'Nextline', '', 'Move again to new line']
print (var.splitlines(1))
# ['Print new line\n', 'Nextline\n', '\n', 'Move again to new line']
lstrip([chars])
从字符串开头删除字符后,返回一个字符串,默认为空格字符

var=' This is a good example '
print (var.lstrip())
# This is a good example
var='*****This is a good example*****'
print (var.lstrip('*'))
# This is a good example**********

rstrip([chars])
从字符串末尾删除字符后,返回一个字符串
其中:Chars =这是要从字符串中修剪的字符。默认为空格字符

var=' This is a good example '
print (var.rstrip())
# This is a good example
var='*****This is a good example*****'
print (var.lstrip('*'))
# *****This is a good example

rindex(str[,i [,j]])
在完整的字符串(如果未定义i和j)或字符串的子字符串(如果已定义i和j)中搜索“ str”。此函数返回提供“ str”的最后一个索引
如果“ str”不存在,则会引发ValueError异常, 其中:i 此索引开始,j 索引结束

var='This is a good example'
str='is'
print (var.rindex(str,0,10))
# 5
print (var.rindex(str,10))
# ValueError: substring not found

len(string)
返回给定String的长度

var='This is a good example'
print (len(var))
# 22



>>> print("%(lang)s is fun!" % {"lang":"Python"})
Python is fun!

>>> "Python is as simple as {0}, {1}, {2}".format("a", "b", "c") 
'Python is as simple as a, b, c' 
>>> "Python is as simple as {1}, {0}, {2}".format("a", "b", "c") 
'Python is as simple as b, a, c' 
>>> xy = {"x":0, "y":10} 
>>> print("Graph a point at where x={x} and y={y}".format(**xy)) 
Graph a point at where x=0 and y=10



format()

# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)

# order using positional argument

positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)

# order using keyword argument

keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')

print(keyword_order)


>>> # formatting integers

>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'
>>> # formatting floats
>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'
>>> # round off
>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'

# out 3.142
pi = 3.141592653589793
n = 3
print(f"%.{n}f" % pi)
print("{0:.{1}f}".format(pi, n))

print(f"{pi:.{n}f}")


>>> # string alignment   左对齐<,右对齐>或^将字符串居中
>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')

'|butter    |  bread   |       ham|'



f'Python {expr}'
expr可以是常量,表达式,字符串或数字或Python对象等形式的任何东西
version = 3.6
feature = 'f-string'

str_final = f'Python {feature} was introduced in version {version}.'
print(str_final)
# Python f-string was introduced in version 3.6.
from datetime import datetime

print(f'Date as F-string:\n{datetime.now()}')
print(fr'Date as raw string:\n{datetime.now()}')
lambda_test = f"{(lambda x: x * 25) (5)}"
print(lambda_test)
# 125
lambda_test = f"{{999}}"
print(lambda_test)
# {999}
lambda_test = f"{{{999}}}"
print(lambda_test)
# {999}

评论

此博客中的热门博文

学习地址

清华大学计算机系课程攻略 https://github.com/PKUanonym/REKCARC-TSC-UHT 浙江大学课程攻略共享计划 https://github.com/QSCTech/zju-icicles https://home.unicode.org/ 世界上的每个人都应该能够在手机和电脑上使用自己的语言。 http://codecanyon.net   初次看到这个网站,小伙伴们表示都惊呆了。原来代码也可以放在网上卖的?!! 很多coder上传了各种代码,每个代码都明码标价。看了下销售排行,有的19刀的卖了3万多份,额di神啊。可以看到代码的演示效果,真的很漂亮。代码以php、wordpress主题、Javascript、css为主,偏前台。 https://www.lintcode.com/ 算法学习网站,上去每天刷两道算法题,走遍天下都不怕。 https://www.codecademy.com/ 包含在线编程练习和课程视频 https://www.reddit.com/ 包含有趣的编程挑战题,即使不会写,也可以查看他人的解决方法。 https://ideone.com/ 在线编译器,可运行,可查看代码示例。 http://it-ebooks.info/ 大型电子图书馆,可即时免费下载书籍。 刷题 https://github.com/jackfrued/Python-100-Days https://github.com/kenwoodjw/python_interview_question 面试问题 https://github.com/kenwoodjw/python_interview_question https://www.journaldev.com/15490/python-interview-questions#python-interpreter HTTP 身份验证 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Authentication RESTful 架构详解 https://www.runoob.com/w3cnote/restful-architecture.html https://www.rosettacode.org/wiki/Rosetta_C...

PDF处理

虚拟pdf打印机 pdfFactory  https://fineprint.com PDFCreator  https://www.pdfforge.org 开源 cutepdf https://www.cutepdf.com/index.htm Doro PDF Writer http://www.the-sz.com/products/doro PdfScribe  https://github.com/stchan/PdfScribe/releases pdf阅读器 Sumatra PDF https://www.sumatrapdfreader.org/ 为什么 Python 用于 PDF 处理  如您所知,PDF 处理属于文本分析。 大多数文本分析库或框架仅使用 Python 设计。 这为文本分析提供了优势。 还有一件事,您永远无法在现有的机器学习或自然语言处理框架中直接处理 pdf。 除非他们为此证明了显式接口。 我们必须先将pdf转换为文本。 我们可以使用下述任何库轻松实现这一点。 在线转换pdf Sejda https://www.sejda.com/pdf-editor 每个文档 200 页的免费限制 https://www.pdf2go.com/ https://tools.pdfforge.org/extract-text PDF24 Tools https://tools.pdf24.org/zh/ 免费且易于使用的在线PDF工具 FreeOCR http://www.paperfile.net/ 适用于Windows的免费光学字符识别软件,支持大多数Twain扫描仪的扫描,还可以打开大多数扫描的PDF和多页Tiff图像以及流行的图像文件格式,FreeOCR输出纯文本,可以直接导出为Microsoft Word格式。 不支持中文 wkhtmltopdf 和 wkhtmltoimage 是使用 QT Webkit 渲染引擎将 HTML 渲染为 PDF 和各种图像格式的命令行工具。这些完全“无头”运行,不需要显示或显示服务。 https://wkhtmltopdf.org/ django-wkhtmltopdf 允许 Django 站点输出动态 PDF。它利用 wkhtmltopdf 库,允许您使用您知道...

安卓 之 apk下载、ADB、 scrcpy

Apk下载 下载离线安装apk https://www.apkmirror.com/ 免费和安全的Android APK下载 https://apkpure.com/ 被暴雷,有植入 https://apps.evozi.com/apk-downloader/ 可以将Google Play( https://play.google.com )中的apk文件所在网址直接下载到台式机和设备上 https://f-droid.org/zh_Hans/ F-Droid 是一个 Android 平台上 FOSS(Free and Open Source Software,自由开源软件)的目录,并提供下载安装支持。使用客户端可以更轻松地浏览、安装及跟进设备上的应用更新。 https://gitlab.com/AuroraOSS/AuroraStore Aurora商店 是Google Play商店的非官方FOSS客户,设计典雅。 Aurora商店不仅下载,更新和搜索Play商店等应用 https://github.com/OpenTracksApp/OpenTracks OpenTracks是一款运动跟踪应用程序,完全尊重您的隐私。 Tasker https://tasker.joaoapps.com/ 是一款适用于Android的应用程序,它可以根据用户定义的配置文件中的上下文、可点击或定时的主屏幕小部件来执行任务。它无需root或特殊的主屏幕就能控制Android设备。 AsciiCam AsciiCam可以从您的相机指向的任何位置实时生成ASCII图像。选择黑白,原色或全彩,拍照,并将其作为图像或HTML共享。您还可以在库中创建ASCII版本的图片,并且每次使用标准相机应用程序拍摄照片时,也可以选择自动生成ASCII版本。 AsciiCam是完全免费和开源的。 Apk1安装器 优化微信apk文件接收体验。 微信收到apk文件会加 ".1" 后缀导致打不开,必须自己手动找到文件重命名去掉后缀。 使用本安装器就可以在微信内,潇洒地点击直接打开。甚至可以在安装器内浏览apk1文件历史接收记录。 ADB ADB全名是 Android Debug Bridge,是开发或使用Android时很常用的工具。可以从电脑通过USB连线到Android手机上 https:...