【Python第6篇】Python中的数据类型——字符串及常用运算、函数

本文详细介绍了Python中的字符串,包括其概念、多种书写方法,如单双引号转换、反斜杠转义、raw string。还讨论了字符串的下标访问,以及字符串的运算,如相加和重复。此外,提到了字符串与数值的互换方法,并列举了常用字符串函数,如长度计算、大小写转换、删除空格以及字符串判断函数。
摘要由CSDN通过智能技术生成

一、字符串的概念

字符串是由字母、符号、数字等组成的一连串字符,一般放在一组单引号或双引号中间。一个字符串的单引号或双引号必须匹配。请看下面的代码示例:

first_name = 'David'
last_name = "Smith"

print(first_name)
# David

print(last_name)
# Smith

如果字符串较长,而且是多行,则可以将该字符串放在一组符号(''',三个单引号)中间。请看下面的代码示例:

print('''
I wandered lonely as a cloud
That floats on high o'er vales and hills,
When all at once I saw a crowd,
A host of golden daffodils;
Beside the lake, beneath the trees,
Fluttering and dancing in the breeze.

Continuous as the stars that shine
And twinkle on the Milky Way,
They stretched in never-ending line
Along the margin of a bay:
Ten thousand saw I at a glance,
Tossing their heads in sprightly dance.

The waves beside them danced, but they
Out-did the sparkling waves in glee:
A poet could not but be gay,
In such a jocund company:
I gazed -and gazed -but little thought
What wealth the show to me had brought:

For oft, when on my couch I lie
In vacant or in pensive mood,
They flash upon that inward eye
Which is the bliss of solitude;
And then my heart with pleasure fills,
And dances with the daffodils.
——(William Wordsworth,1770-1850)
''')

二、字符串的书写方法

1. 字符串内含有引号的书写方法

由于字符串首尾都需要加引号,因此,如果字符串内含有引号,则需要通过下列方法来处理:

(1) 如果字符串内含有单引号,则需要将字符串放在双引号中间。

(2) 如果字符串内含有双引号,则需要将字符串放在单引号中间。

(3)在字符串内的引号前加上转义符\(反斜杠,backslash)。

(4)在字符串引号前加上字母r,r在这里表示raw string,将不转义字符串内任何内容。

请看下面的代码示例:

单双引号转换:

string1 = 'This is the slogan: "Life is short, I use Python!"'
print(string1)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值