【Python入门第九天】Python 字符串

本文详细介绍了Python中的字符串,包括字符串字面量、赋值、多行字符串、字符串作为字符数组、裁切、负索引、长度计算、字符串方法如strip、lower、upper、replace、split等,以及字符串的检查、串联和格式化。强调了字符串是不可变的,所有方法都不会改变原始字符串。
摘要由CSDN通过智能技术生成

字符串字面量

python 中的字符串字面量由单引号或双引号括起。

‘hello’ 等同于 “hello”。

可以使用 print() 函数显示字符串字面量:

实例

print("Hello")
print('Hello')

运行实例

用字符串向变量赋值

通过使用变量名称后跟等号和字符串,可以把字符串赋值给变量:

实例

a = "Hello"
print(a)

运行实例

多行字符串

可以使用三个引号将多行字符串赋值给变量:

实例

可以使用三个双引号:

a = """Python is a widely used general-purpose, high level programming language. 
It was initially designed by Guido van Rossum in 1991 
and developed by Python Software Foundation. 
It was mainly developed for emphasis on code readability, 
and its syntax allows programmers to express concepts in fewer lines of code."""
print(a)

运行实例

或三个单引号:

实例

a = '''Python is a widely used general-purpose, high level programming language. 
It was initially designed by Guido van Rossum in 1991 
and developed by Python Software Foundation. 
It was mainly developed for emphasis on code readability, 
and its syntax allows programmers to express concepts in fewer lines of code.'''
print(a)

运行实例

注释:在结果中,换行符插入与代码中相同的位置。

字符串是数组

像许多其他流行的编程语言一样,Python 中的字符串是表示 unicode 字符的字节数组。

但是,Python 没有字符数据类型,单个字符就是长度为 1 的字符串。

方括号可用于访问字符串的元素。

实例

获取位置 1 处的字符(请记住第一个字符的位置为 0):

a 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值