6、字符串
在Python中字符串的使用频率非常高,而且非常受到欢迎,那么之前有说过,字符串呢需要使用引号框起来
数组应该都比较熟悉,我们在输出数组的时候,比如:
a = {1,2,3,4,5}
print(a[0])
print(a[1])
分别会输出1 2两个数据
不做过多解释,数组的下标都是从0开始的。
其实字符串也有类似的效果,例如我有这样的一串字符串变量:
a = "My name is Daofengql."
我同样也可以输出一个字符,如:
print(a[0])
print(a[1])
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/85cb92dad52e489244c948c72b913d2e82972618.png)
不止可以取单一字符,也可以取范围数据
如区间,我们显示位置2-10的字符()
同样是这串字符串
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/9b0be2f362ba80b3b7106d3b43eedc8882e5c0cc.png)
不止取范围,还有大小写转化,取字符串长度,去除头尾空格,关键字符分割,关键字替换
大小写:
同一个变量。使用 .upper方法 全部大写化
a = "My name is Daofengql."
print(a.upper())
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/ed229b5cf8e79880474ba56e60bd0532b8f2e0c1.png@898w_278h.png)
同一个变量,使用 .lower方法 全部小写化
a = "MY NAME IS DAOFENGQL."
print(a.lower())
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/282946e413fbccbd4b7236986ac7d4628f53b4ad.png@1210w_1210h.png)
取长度:
使用len()函数
a = "MY NAME IS DAOFENGQL."
print(len(a))
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/06c6fee0d3a98e29440012b0b1462b027c5a3aae.png@1210w_1210h.png)
删除头尾空格:
使用.strip方法
a = " MY NAME IS DAOFENGQL. "
print(a.strip())
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/2e3a449cad1740a7b294b0621b8998446abb1cc4.png@1210w_1210h.png)
字符串分割:
使用 .split方法来实现
a = "He,She,It"
print(a.split(",")) #分割依据 ","
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/537f76afc26fd52457abfba414c8c8e0b3d054eb.png@666w_226h.png)
字符替换:
使用 .replace方法,可以对字符串内的指定内容进行一个替换操作
a = "He is a very bad buy."
print(a.replace("bad","good")) #将bad字符替换成good
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/d44e29f4a4c3b762d05d65ba46d53d4311c06712.png@604w_134h.png)
7、从命令中获取数据(命令行输入)
首先我们新建一个文件,我们可以命名为input_test.py
打开,在里面输入如下代码:
print("Enter a String:")
n=input()
print("My name is ", n)
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/b0e31c4603512f0c436d7b93b5e7b8286be48b13.png@1210w_1210h.png)
在上方run中 run module
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/690c2b701d3619014ef60e9771f025dac00175c6.png@1320w_984h.png)
内容可以是任何文字,因为我们type一下这个变量
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/7839dda9908d4ea0f3259187424484e018611ae0.png@1210w_1210h.png)
输入的数据保存进变量,是以字符串类型储存的。结合前面所述,我们可以在需要的时候,进行一个强制类型转换操作
最后演示一个多个输入拼接:
print("Enter a String:")
n1 = input()
print("Enter a String:")
n2 = input()
print("Enter a String:")
n3 = input()
print("Enter a String:")
n4 = input()
print(n1+n2+n3+n4)
![](http://objectstorage.global.loongapi.com/loongapiSources/picbed/olddata2/2021/02/ce94443df590e4eeeb6a343d390d10363e235794.png@1210w_1210h.png)
评论 (0)