字符串介绍


1、字符串在内存中的存储;

2、字符串相加;

3、字符串的格式化;

In [1]: a = 100 

In [2]: a
Out[2]: 100 #100<255,在堆内存下占用了一个字节,一个字节8位,可以存放的数值最大为255。 In [3]: b = "" In [4]: b
Out[4]: '' #对应ASCII码存放,一个字节存放任何的一个字符,因此字符串100对应3个字符即占用3个字节。字符串占用空间大。 In [5]: type(a)
Out[5]: int In [6]: type(b)
Out[6]: str
In [4]: b =  ''
In [7]: c = ""
In [8]: b + c
Out[8]: ''
In [9]: d = "b+c=%s" %(b+c)

In [10]: d
Out[10]: 'b+c=100200'
In [11]: e="abcefg%sgfgfgfg"%b

In [12]: e
Out[12]: 'abcefg100gfgfgfg'

下标索引:就是编号,通过这个编号能找到相应的存储空间。

字符串中下标的使用:字符串实际上就是字符的数组,所以也支持下标索引。

In [27]: name
Out[27]: 'abcdefghijk' In [28]: name[0]
Out[28]: 'a' In [29]: name[-1]
Out[29]: 'k' In [30]: len(name)
Out[30]: 11 In [32]: name[len(name)-1]
Out[32]: 'k' In [33]: name[-10]
Out[33]: 'b' In [34]: name[10]
Out[34]: 'k'

切片:是指对操作对象截取其中一部分的操作,字符串、列表、元组都支持切片操作

切片的语法:【起始:结束:步长】

步长是下标变化的规律,默认为1

注意:选取的区间属于左闭右开型(包头不包尾)

In [1]: name="abdfsdfsdf"

In [2]: name[1:4]
Out[2]: 'bdf' In [3]: name[:]
Out[3]: 'abdfsdfsdf' In [4]: name[::2]
Out[4]: 'adsfd' In [5]: name[0:]
Out[5]: 'abdfsdfsdf' In [6]: name[:-1]
Out[6]: 'abdfsdfsd'

将输入的字符串倒序输出

  1 s=input("请输入一个字符串:")
2 i=len(s)
3 while i > 0 :
4 i -= 1
5 print("%s"%(s[i]),end="")
6 print("")
[root@localhost python]# python3 20.py
请输入一个字符串:love
evol
[root@localhost python]#

通过切片实现字符串倒序输出

In [1]: name="asdsadsds"

In [2]: name
Out[2]: 'asdsadsds' In [3]: name[-1::-1]
Out[3]: 'sdsdasdsa'

字符串操作:函数调用的操作

In [9]: name="love"

In [10]: name. //按Tab键显示字符串的方法
name.capitalize name.encode name.format name.isalpha name.islower name.istitle name.lower
name.casefold name.endswith name.format_map name.isdecimal name.isnumeric name.isupper name.lstrip
name.center name.expandtabs name.index name.isdigit name.isprintable name.join name.maketrans >
name.count name.find name.isalnum name.isidentifier name.isspace name.ljust name.partition

查找方法:find()和index()

In [10]: my_str="hello world zyj sl everyone in the world"

In [11]: my_str.find("zyj")
Out[11]: 12 #目标字符串的第一个字符所在的下标位 In [12]: my_str.find("lw")
Out[12]: -1 #找不到时返回-1,当返回小于0时,即可判断没有找到。 In [13]: my_str.find("world")
Out[13]: 6 #默认从左边开始查找,并输出第一个找到的位置 In [14]: my_str.rfind("world")
Out[14]: 35 #.rfind方法从右边开始查找 In [15]: my_str.index("world")
Out[15]: 6 #index()默认从左边查找 In [17]: my_str.rindex("world")
Out[17]: 35 #rindex()从右边查找 In [16]: my_str.index("lw")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-a951699b322b> in <module>()
----> 1 my_str.index("lw") ValueError: substring not found #查找不到时报错,与find()的区别

计数及替换方法:count()和replace()

In [18]: my_str.count("world")#计算目标元素出现的次数。
Out[18]: 2 In [19]: my_str.count("lw")
Out[19]: 0 In [20]: my_str.count("zyj")
Out[20]: 1 In [21]: my_str.replace("hello","Hi")
Out[21]: 'Hi world zyj sl everyone in the world' In [22]: In [22]: my_str
Out[22]: 'hello world zyj sl everyone in the world' #原字符串没有改变 In [23]: my_str.replace("world","city")#默认替换所有查找到的目标元素
Out[23]: 'hello city zyj sl everyone in the city' In [24]: my_str.replace("world","city",1) #将查找到的第一个替换,指定count,则替换不超过count次。
Out[24]: 'hello city zyj sl everyone in the world'

分隔:split(),以str为分隔符切片mystr,可以指定最多分割成多少个段。

In [25]: my_str
Out[25]: 'hello world zyj sl everyone in the world' In [26]: my_str.split(" ") #以空格作为分隔符
Out[26]: ['hello', 'world', 'zyj', 'sl', 'everyone', 'in', 'the', 'world'] In [29]: my_str.split() #默认以空格作为分隔符,返回的是列表
Out[29]: ['hello', 'world', 'zyj', 'sl', 'everyone', 'in', 'the', 'world'] In [27]: my_str.split(" ",2) #指定最多包含两个分隔符
Out[27]: ['hello', 'world', 'zyj sl everyone in the world'] In [28]: my_str.split("zyj")
Out[28]: ['hello world ', ' sl everyone in the world'] #结果中不显示“zyj”,把它当作分隔符了。 In [30]: my_str.partition("zyj")
Out[30]: ('hello world ', 'zyj', ' sl everyone in the world') #将本身也作为一个元素,与split()的区别,包含隔开符。
分隔:partition()注意与split()的区别。
In [25]: my_str
Out[25]: 'hello world zyj sl everyone in the world' In [36]: my_str.partition() #不支持这种写法,必须指定分隔标志。
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-36-c027286912d6> in <module>()
----> 1 my_str.partition() TypeError: partition() takes exactly one argument (0 given) In [37]: my_str.partition(" ") #以空格作为分隔符,遇到的第一个空格作为分隔符,自身也是分隔元素
Out[37]: ('hello', ' ', 'world zyj sl everyone in the world') In [38]: my_str.partition(' ',3) #不支持设置最大分隔数
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-86d354aca67f> in <module>()
----> 1 my_str.partition(' ',3) TypeError: partition() takes exactly one argument (2 given)

capitalize():把字符串的第一个字符大写。

title():将每个字符串的第一个单词大写

In [41]: my_str.capitalize()
Out[41]: 'Hello world zyj sl everyone in the world' In [42]: my_str.title()
Out[42]: 'Hello World Zyj Sl Everyone In The World'

startswith():检查字符串以什么开头,返回布尔值:True或False

endswith():检查字符串以什么开头,返回布尔值:True或False

In [43]: my_str.startswith("hello")
Out[43]: True In [44]: my_str.startswith("Hello")
Out[44]: False In [45]: my_str.endswith("wor")
Out[45]: False In [46]: my_str.endswith("world")
Out[46]: True #使用场景
In [50]: file_name="XXX.txt" In [52]: if file_name.endswith(".txt"):
...: print("文本文件")
...:
文本文件
In [53]:

lower():将字符串中的所有大写字符变为小写;

upper():将字符串中的所有小写字母变为大写;

In [57]: my_str
Out[57]: 'Hello WEWER dsfsdf dfsdf' In [58]: my_str.upper()
Out[58]: 'HELLO WEWER DSFSDF DFSDF' In [59]: my_str.lower()
Out[59]: 'hello wewer dsfsdf dfsdf' #应用场景,验证码不区分大小写,用户输入的进行转换。
In [61]: str="ABC" #目标字符串 In [62]: user_str="Abc" #用户输入字符串 In [63]: user_str.upper() #对用户输入的进行转换后比较
Out[63]: 'ABC'

排列对齐操作:ljust() rjust() center()

In [66]: name
Out[66]: 'ddsfsdfsdfdfdsf' In [67]: name.ljust(50) #50代表长度,返回一个使用空格填充至长度的新字符串
Out[67]: 'ddsfsdfsdfdfdsf ' In [68]: In [68]: name.rjust(50)
Out[68]: ' ddsfsdfsdfdfdsf' In [69]: name.center(50)
Out[69]: ' ddsfsdfsdfdfdsf ' In [70]:

删除空白字符:lstrip()   rstrip()  strip()

In [70]: name=" abc  "

In [71]: name.lstrip() #删除左边的空白符
Out[71]: 'abc ' In [72]: name.rstrip() #删除右边的空白符
Out[72]: ' abc' In [73]: name.strip() #删除左右两侧空白符 strip()=trim() java中使用trim()
Out[73]: 'abc' In [74]:

换行符隔开:splitlines()

In [76]: lines="anbc\ndfsdfdf\ndfsdfdf\ndfdf"

In [77]: lines.splitlines()
Out[77]: ['anbc', 'dfsdfdf', 'dfsdfdf', 'dfdf'] In [78]: lines.split("\n")
Out[78]: ['anbc', 'dfsdfdf', 'dfsdfdf', 'dfdf'] In [79]:

字符串中只包含数字、字母、数字或字母、空格的操作,返回布尔值 isalnum() isalpha() isdigit() isspace()

In [1]: test="122323dsfdfsdfsdf"

In [2]: test.isalnum()
Out[2]: True In [3]: test.isalpha()
Out[3]: False In [4]: test.isdigit()
Out[4]: False In [5]: test.isspace()
Out[5]: False In [6]: In [6]: test1=" " In [7]: test1.isspace()
Out[7]: True

mystr.join(list):mystr中每个字符后面插入list的每个元素后面,构造出一个新的字符串

应用:将列表转换为字符串

In [8]: names=["","",""]

In [9]: names
Out[9]: ['', '', ''] In [10]: "".join(names)
Out[10]: '' In [11]: "-".join(names)
Out[11]: '100-200-300'

查看方法的帮助文档:

In [16]: test="122323dsfdfsdfsdf"

In [14]: help(test.find)

find(...) method of builtins.str instance
S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.

(面试题)给定一个字符串,返回使用空格或者\r \t分割后的倒数第二个字串。

In [1]: name="hel eewrje\twrjwer\twerwer ew\nrewr"

In [6]: help(name.split)

In [7]: name.split() #会将字符串中的空格以及特殊意义的符号作为分隔符。
Out[7]: ['hel', 'eewrje', 'wrjwer', 'werwer', 'ew', 'rewr'] In [8]: name.split()[-2] #返回的是列表。列表支持下标操作。
Out[8]: 'ew'

python字符串及字符串操作的更多相关文章

  1. Python 基礎 - 字符串常用操作

    字符串常用操作 今天就介紹一下常用的字符串操作,都是以 Python3撰寫的 首字母變大寫 #!/usr/bin/env python3 # -*- coding:utf-8 -*- name = & ...

  2. Python基础(二) —— 字符串、列表、字典等常用操作

    一.作用域 对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用. 二.三元运算 result = 值1 if 条件 else 值2 如果条件为真:result = 值1如果条件为 ...

  3. Python第一天——入门Python(2)字符串的简单操作

    数据的操作 字符串的一些常用操作: 1 1 #!/usr/bin/env python 2 # #coding=utf-8 3 # 4 # test='hello world' 5 # print(t ...

  4. python中关于字符串的操作

    Python 字符串操作方法大全 python字符串操作实方法大合集,包括了几乎所有常用的python字符串操作,如字符串的替换.删除.截取.复制.连接.比较.查找.分割等,需要的朋友可以参考下 1. ...

  5. Python字符串的相关操作

    1.大小写转换 判断字符串 s.isalnum() #所有字符都是数字或者字母 s.isalpha() #所有字符都是字母 s.isdigit() #所有字符都是数字 s.islower() #所有字 ...

  6. Python中对字符串的操作

    Python字符串的相关操作 1.字符串格式判断 s.isalnum() #所有字符都是数字或者字母 s.isalpha() #所有字符都是字母 s.isdigit() #所有字符都是数字 s.isl ...

  7. Python自动化开发 - 字符串, 列表, 元组, 字典和和文件操作

    一.字符串 特性:字符串本身不可修改,除非字符串变量重新赋值.Python3中所有字符串都是Unicode字符串,支持中文. >>> name  = "Jonathan&q ...

  8. Python中的字符串操作总结(Python3.6.1版本)

    Python中的字符串操作(Python3.6.1版本) (1)切片操作: str1="hello world!" str1[1:3] <=> 'el'(左闭右开:即是 ...

  9. Python入门之 字符串操作,占位符,比较大小 等

    Python  字符串 常用的操作 切片 左包括右不包括的原则 ________________ 比较字符串大小 eg: cmp("a",'b')   -1第一个比第二个小  0 ...

  10. Python字符串的简单操作

    数据的操作 字符串的一些常用操作: 1 1 #!/usr/bin/env python 2 # #coding=utf-8 3 # 4 # test='hello world' 5 # print(t ...

随机推荐

  1. The project was not built since its build path is incomplete. Cannot find the class file for java.lang.Object

    The project was not built since its build path is incomplete. Cannot find the class file for java.la ...

  2. Ubuntu 安装 samba 实现文件共享和source insight 阅读uboot

    环境:win10 + 虚拟机Ubuntu 12.04 一. samba的安装: # sudo apt-get install samba # sudo apt-get install smbfs 二. ...

  3. SQLServer数据库权限设置--保障数据库安全

    一.登陆界面引入 下图为SQL Server的登陆界面. 1)服务器名称:“.”代表本地计算机,选择下拉框,可以看见还有一个与本机机名相同的内容,也代表于本地服务器连接:要连接远程服务器的话,在此处填 ...

  4. 「CF744C」Hongcow Buys a Deck of Cards「状压 DP」

    题意 你有\(n\)个物品,物品和硬币有\(A\),\(B\)两种类型,假设你有\(M\)个\(A\)物品和\(N\)个\(B\)物品 每一轮你可以选择获得\(A, B\)硬币各\(1\)个,或者(硬 ...

  5. JavaScript -- 数据存储

    Cookie Web应用程序是使用HTTP协议传输数据的.HTTP协议是无状态的协议. 一旦数据交换完毕,客户端与服务器端的连接就会关闭,再次交换数据需要建立新的连接.这就意味着服务器无法从连接上跟踪 ...

  6. Codeforces Round #523 (Div. 2)C(DP,数学)

    #include<bits/stdc++.h>using namespace std;long long a[100007];long long dp[1000007];const int ...

  7. Vue里的nextTick方法

    官方解释: 在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法,获取更新后的 DOM. 自己总结: `Vue.nextTick(callback)`,当数据发生变化,更新后执 ...

  8. Luogu P2833 等式 我是傻子x2

    又因为调一道水题而浪费时间...不过细节太多了$qwq$,暴露出自己代码能力的不足$QAQ$ 设$d=gcd(a,b)$,这题不是显然先解出来特解,即解出 $\frac{a}{d}x_0+\frac{ ...

  9. Testing Round #12 B

    Description A restaurant received n orders for the rental. Each rental order reserve the restaurant ...

  10. 自动化测试 - Appium + Python史上最全最简环境搭建步骤

    一,为什么是Appium借一张图: 1.1 Appium优点 l  开源 l  跨架构:NativeApp.Hybird App.Web App l  跨设备:Android.iOS.Firefox ...