AI教程网 - 未来以来,拥抱AI;新手入门,从AI教程网开始......

Python拼接与截断字符串(切片slice)

Python字符串 AI君 57℃

1、拼接字符串

变量可以引用,可以拼接(同类型的数据之间拼接可以用“+”;不同类型的数据直接拼接用“,”会用一个空格;不同类型的属性强制转换到一起 )

age=20

name=”露露”

  sex=”girl”

print(name+”是”+sex) #都是string类型

print(name+”今年”,age)    #不同类型 string与int

print(name+”今年”+str(age))

只拼接一个直接逗号分隔,逗号后面有个空格

num = 100
aNum = 1
total = 0
while aNum <= num:
    total = total + aNum
    aNum += 1
# 拼接多个字符串用如下格式
print('1 到 %d 的和为%d -- %s' % (num, total, "hellowlrld"))
# 只拼接一个直接逗号分隔,逗号后面有个空格 即可
print('hhaa', total)
  • 或者如下格式的拼接

  • 常犯错误字符串与非字符串连接
num_eggs = 12
print('I have ' + num_eggs + ' eggs.')
  • 导致:TypeError: cannot concatenate ‘str’ and ‘int’ objects
  • 正确做法:
num_eggs = 12
print('I have ' + str(num_eggs) + ' eggs.')
  • 或者
num_eggs = 12
print('I have %s eggs.' % (num_eggs))

 

2、截断字符串(切片)

切片操作可以从一个字符串中获取子字符串(字符串的一部分)。我们使用一对方括号、起始偏移量start、终止偏移量end 以及可选的步长step 来定义一个分片。

格式: [start:end:step]

• [:] 提取从开头(默认位置0)到结尾(默认位置-1)的整个字符串
• [start:] 从start 提取到结尾
• [:end] 从开头提取到end – 1
• [start:end] 从start 提取到end – 1
• [start:end:step] 从start 提取到end – 1,每step 个字符提取一个
• 左侧第一个字符的位置/偏移量为0,右侧最后一个字符的位置/偏移量为-1

几个特别的examples 如下:

  1. 提取最后N个字符:
>>> letter = 'abcdefghijklmnopqrstuvwxyz'
>>> letter[-3:]
'xyz'

2、从开头到结尾,step为N:

>>> letter[::5]
'afkpuz'

3、将字符串倒转(reverse), 通过设置步长为负数:

>>> letter[::-1]
'zyxwvutsrqponmlkjihgfedcba'

name=‘here we are again?‘

print(name[:6])

  • 正向取值索引  从0开始的  取下不取上 [0,3)   (左下右上/过头不过尾  半闭半开空间)

print(name[0:3])

print(name[0:])一直输出到结尾

  • 从尾巴开始取值

print(name[:-1]) 负一从右边开始数,here we are again

print(name[-4:-1])   ain

 

 

a=4

b=3.1456789

print(type(a))

print(type(b))

整型、浮点型、布尔型、None  格式化输出

name=’hlz’

print(“输出的姓名是:%s”%name)   格式化输出%s 一个占位符

print(“输出的小数只有2位%.2f”%b)     .2f小数只取两位

作业1:输入一个标准的日期如(20160503),打印对应的年月日即2016年05月03日”’ a=input(“请输入对应的日期”)

字符串切片可阅读相关文章:https://blog.csdn.net/u011349387/article/details/49122931

https://blog.csdn.net/lvxiaoting/article/details/79957235 

https://www.cnblogs.com/virus1102/p/5325978.html

作者:qq_42492845
原文链接:https://blog.csdn.net/qq_42492845/article/details/81509399

转载请注明:www.ainoob.cn » Python拼接与截断字符串(切片slice)

喜欢 (0)or分享 (0)