字符串方法python|-Python基础教程(二)字符串和函数 - Hello&#34

📅 2026-11-30 👤 拼多多助力营销技巧 📂 pdd帮助力 👁️ 497 次阅读

6.字符串

6.1 字符串的表示方式

6.1.1 普通字符串

普通字符串指用单引号('')或双引号(”")括起来的字符串。例如:'Hello'或"Hello"

>>> 'Hello'

'Hello'

>>> "Hello"

'Hello'

>>> s='\u0048\u0065\u006c\u006c\u006f'

>>> s

'Hello'

>>> "Hello'world"

"Hello'world"

>>> 'Hello"world'

'Hello"world'

6.1.2 原始字符串

在 Python 中,以字母 r 或者 R 作为前缀的字符串,例如 r'...'和R'...',被称为原始字符串。

>>> s='hello\tworld\nPython\t3'

>>> print(s)

hello world

Python 3

>>> s=r'hello\tworld\nPython\t3'

>>> print(s)

hello\tworld\nPython\t3

6.1.3 长字符串

使用三个单引号(''')或三个双引号(""")括起来.

>>> s='''

xxx

bfdzbd

dfbd

dfbd

'''

>>> s

'\n xxx\n bfdzbd\n dfbd\n dfbd\n '

>>> print(s)

xxx

bfdzbd

dfbd

dfbd

6.2 字符串与数字相互转换

6.2.1 将字符串转换为数字

>>> int("10")

10

>>> int("10.2") #类型不同不能转换

Traceback (most recent call last):

File "", line 1, in

ValueError: invalid literal for int() with base 10: '10.2'

>>> float("10.2") 拼多多帮助力入口

10.2

>>> int("ab") #类型不同不能转换

Traceback (most recent call last):

File "", line 1, in

ValueError: invalid literal for int() with base 10: 'ab'

>>> int("ab",16) #按十六进制进行转换

171

6.2.2 将数字转换为字符串

>>> str(12)

'12'

>>> str(12.3)

'12.3'

>>> str(True)

'True'

6.3 格式化字符串

Python的字符串可通过占位符%、format ()方法和f-strings三种方式实现格式化输出。

6.3.1 占位符%,字符串方法python

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧