007、字符串
本文最后更新于 68 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com

字符串

字符串生成

用一对单引号或者双引号来生成字符串:

"hello world!"
'hello world!'
'hello world!'
'hello world!'

可以在字符串里的引号前加一个转义符号“\”,表示字符串中的引号:

"I\'m good at Python!"
"I'm good at Python!"

数学运算

加法与数字乘法:

"hello" + "world"
'helloworld'
'abc' * 3
'abcabcabc'

长度:

len('hello world!')
12

方法

.split()方法分割:

"1 2 3 4    5".split()
['1', '2', '3', '4', '5']

更换分隔符:

"1,2,3,4,5".split(",")
['1', '2', '3', '4', '5']

指定最大分割次数:

"1,2,3,4,5".split(",", 2)
['1', '2', '3,4,5']

.rsplit()方法从后向前分割:

"1,2,3,4,5".rsplit(",", 2)
['1,2,3', '4', '5']

.join()方法连接:

nums = ['1', '2', '3', '4', '5']
":".join(nums)
'1:2:3:4:5'

.replace()方法替换:

s = 'hello world'
s.replace("world", "python")
'hello python'

替换不会改变原来字符串的值:

s
'hello world'

.find()方法查找单词:

"hello world".find("world")
6

.upper().lower()方法大小写:

"hello world".upper()
'HELLO WORLD'
"HELLO WORLD".lower()
'hello world'

.strip()方法去除空白字符:

"  HELLO WORLD    \n\t".strip()
'HELLO WORLD'

.lsplit().rsplit()方法只去除某一边的空白字符:

"  HELLO WORLD    ".lstrip()
'HELLO WORLD    '
"  HELLO WORLD    ".rstrip()
'  HELLO WORLD'

去除指定的字符,可以指定多个:

"==-==HELLO--=--".strip("=-")
'HELLO'

与数字的转换

数字转字符串:

str(12.3)
'12.3'
bin(255)
'0b11111111'
oct(255)
'0o377'
hex(255)
'0xff'

字符串转数字:

int('255')
255
float('2.5')
2.5
int('0b11111111', 2)
255

格式化

占位符与百分号进行格式化:

name, age = 'John', 10
'%s is %d years old.' % (name, age)
'John is 10 years old.'

.format()方法格式化:

'{} is {} years old.'.format(name, age)
'John is 10 years old.'

f字符串:

f'{name} is {age} years old.'
'John is 10 years old.'

格式化的时候指定格式:

acc = 0.9131
model_name = "my_model"
epoch = 92

冒号后面指定,>10s表示长度为10的字符串,>在前面补空格,03d表示长度为3、前面补0的整数,.2f表示保留2位小数的浮点数。=号会将前面的变量名一起打出来,且f字符串的变量名支持输入运算表达式。

f'train {model_name.upper():>10s}, {epoch=:03d}, {acc=:.2f}'
'train   MY_MODEL, epoch=092, acc=0.91'
谨此笔记,记录过往。凭君阅览,如能收益,莫大奢望。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇