跳至主要内容

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...

MechanicalSoup

用于自动与网站交互的 Python 库。 MechanicalSoup 自动存储和发送 cookie,跟踪重定向,并且可以跟踪链接和提交表单。 它不执行 JavaScript。 https://github.com/MechanicalSoup/MechanicalSoup https://mechanicalsoup.readthedocs.io/en/stable/index.html https://realpython.com/python-web-scraping-practical-introduction/ pip show Mechanicalsoup 找到模块的安装位置 https://stackoverflow.com/questions/54352162/download-file-with-mechanicalsoup # Install dependencies # pip install requests # pip install BeautifulSoup4 # pip install MechanicalSoup # Import libraries import mechanicalsoup import urllib.request import requests from bs4 import BeautifulSoup import re # Create a browser object that can collect cookies browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.ons.gov.uk/economy/grossdomesticproductgdp/timeseries/l2kq/qna") browser.download_link(link_text=".xls",file="D:/ONS_Data.xls" )

安装和卸载软件(msi\exe)

如何判断一个软件是64位的还是32位的? 情况1、 未安装--右键安装程序查看属性,兼容性,勾选兼容模式查看最低适配是vista的是64位,反之32位, 不太准确 情况2、 已安装--运行软件,64位操作系统打开任务管理器看进程后缀名,带*32就是32位,反之64位 https://www.joci.net/xxbk/126251/ FileMon 和 Regmon 不再可供下载。从Windows 2000 SP4,Windows XP SP2,Windows Server 2003 SP1和Windows Vista开始的Windows版本上,它们已被 Process Monitor 取代 https://adamtheautomator.com/procmon/ Process Monitor 是Windows的高级监视工具,它显示实时文件系统,注册表和进程/线程活动。 它结合了两个旧的Sysinternals实用程序 Filemon 和  Regmon的功能 ,并添加了广泛的增强功能列表,包括丰富的和非破坏性的过滤,全面的事件属性(例如会话ID和用户名),可靠的过程信息,带有集成符号的完整线程堆栈支持每个操作,同时记录到文件等。 它独特的强大功能将使Process Monitor成为您的系统故障排除和恶意软件搜索工具包中的核心实用程序。 https://wikileaks.org/ciav7p1/cms/page_42991626.html HKLM\Software\Microsoft\Cryptography\MachineGuid Machine GUID/Cryptography GUID---该密钥通常用作机器的唯一标识符。它也已用于将两台计算机链接在一起-在某些情况下,计算机GUID是与设备(MP3播放器等)一起传递的。 Machine GUID不是唯一 https://docs.microsoft.com/zh-cn/windows/win32/properties/props-system-identity-uniqueid?redirectedfrom=MSDN UniqueID才是唯一 注册表 是存储系统和应用程序的设置信息 打开注册表的方式很简单:cmd中输入regedit 卸载路径只有一个 已安装32位的程序,如果是系统是32位...