2025年python中helloworld 获取llow_Python学习日记---字符串

python中helloworld 获取llow_Python学习日记---字符串一 字符序列 Python 字符型变量与其他语言有所不同 因为特殊的命名空间 使得字符串是不可直接更改的 如何指定显示字符串中特定位置的值 如下 gt gt gt helloString Hello World gt gt gt helloString 0

大家好,我是讯享网,很高兴认识大家。

一、字符序列

Python字符型变量与其他语言有所不同,因为特殊的命名空间,使得字符串是不可直接更改的

如何指定显示字符串中特定位置的值?如下

>>> helloString = "Hello World"

>>> helloString[0]

'H'

>>> helloString[5]

' '

>>> helloString[-1]

'd'

>>> helloString[-5]

'W'

由示例可知,方括号[]内的值表示特定位置自左向右 0,1,2....自右向左 -1,-2,-3....

二、索引和分片

Python采用的事半开区间,包含范围内的起始值,不包含结束值

1.普通的分片和索引

>>> helloString = "Hello World"

>>helloString[:]    #默认值起始位置为0,结束位置为最后元素的后一位置

'Hello World'

>>> helloString[2:5]

'llo'

>>> helloString[2:-2]

'llo Wor'

>>>helloString[-1]   #只有一个参数则用作起始位置,结束位置为默认值

'd'

2.扩展分片

分片还可以加入第三个参数,指定分片的步长,就是从当前字符和下一字符相隔字符数,默认为1

,当步长为负数时,则表示从串尾部往前提取。示例如下:

>>> digits = "0"

>>> digits[::-1]  #从尾部向前提取,在回文中使用较多

''

>>> digits[1::2]   #得到奇数分片

'13579'

>>> digits[0::2]  #得到偶数分片

'02468'

>>> digits[-2::-2]

'86420'

>>> digits[-1::-2]

'97531'

3.复制分片

>>> nameOne = "openex"


讯享网

>>> nameTwo = nameOne[::-1]

>>> id(nameOne),id(nameTwo)

(, )

>>> nameOne,nameTwo

('openex', 'xenepo')

三、字符串操作

1.“+” 运算符可用作两字符串连接  “*” 运算符可用作字符串的复制

>>> A = "Hello"

>>> B = "World"

>>> A+B

'HelloWorld'

>>> A*2+(" "+B)*3

'HelloHello World World World'

2.in运算符

可用于检测一字符串中是否包含一个字符串

>>>'ab' in 'xxxxxabcc'

True

3.字符串函数和方法

函数的使用与C差别不大,方法类似于C++的方法概念如helloString.upper().find("A",1,8)

四、字符串的格式化输出

>>>import math

>>> print ("%-10s,%10s\n%-5d,%5d\n%-8.2f,%.4f"%("ABC","ABC",123,123,math.pi,math.pi))

ABC       ,       ABC

123  ,  123

3.14    ,3.1416

#类似C语言的printf格式化输出, %[符号][宽度][.精度]code

五、一个回文测试示例:

不区分大小写

无视特殊符号,只比较数字和字母

import string

TestString = input("Please input the string for test: ")

TestString = TestString.lower() #将字符串中字母变为小写

junk = string.punctuation+string.whitespace #利用预定义字符串,生成特殊符号集合

for char in junk:

if(char in TestString):

TestString = TestString.replace(char, "") #字符串替换方法,将char换成""

if(TestString == TestString[::-1]):

print("%s\n%s"%(TestString,TestString[::-1]))

else:

print("IT's not a palindrome\nONE1:%s\nONE2:%s"%(TestString,TestString[::-1]))

小讯
上一篇 2025-03-05 21:50
下一篇 2025-04-10 09:03

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/95188.html