当前位置: 移动技术网 > IT编程>脚本编程>Python > Python入门笔记——字符串

Python入门笔记——字符串

2020年07月26日  | 移动技术网IT编程  | 我要评论
目录一.字符串的创建二.转义字符三.字符串运算四.字符串的格式化一.字符串的创建python的字符串以’‘或者""或者’’’’’'括起来的随意文本都是字符串str1 = 'I love you'str2 ="hello"str3 = '''hello world''' 二.转义字符需要在字符中使用特殊字符时,需要用反斜杠()转义字符``>>> word = "I\'m Liming">>> print(word)I'm Liming三.字符串运

一.字符串的创建

python的字符串以’‘或者""或者’’’’’'括起来的随意文本都是字符串

str1 = 'I love you'
str2 ="hello"
str3 = '''hello world''' 

二.转义字符

需要在字符中使用特殊字符时,需要用反斜杠()转义字符``

>>> word = "I\'m Liming"
>>> print(word)
I'm Liming

在这里插入图片描述

三.字符串运算

字符串连接

>>> str1 = 'hello'
>>> str2 = 'world'
>>> str3 = str1 + str2
>>> print(str3)
helloworld

字符串合并

>>> url = ['www','python','org']
>>> print('.'.join(url))
www.python.org

重复输出字符串

>>> str1 = 'hello'
>>> print(str1*2)
hellohello

字符串的切片

>>> str = 'today is a busy day'
>>> print(str[0:5]) #从第一个字符开始取到第五个
today
>>> print(str[-3:]) #从倒数第三个取到最后一个
day
>>> print(str[::]) #从第一个取到最后一个
today is a busy day

字符串的分割

>>> myphone = '1314-159-26'
>>> print(myphone.split('-'))
['1314', '159', '26']

字符串的索引

>>> str1 = 'hello my lover'
>>> print(str1[0]) #取出第一个字符
h

字符串的查找

>>> str = 'this is my hello world'
>>> print(str.find('my')) #若找不到,返回-1
8

计算字符串的长度

>>> str = 'this is my hello world'
>>> len(str)
22

四.字符串的格式化

%运算符就是用来格式化字符串的。字符串内部,%s表示用字符串替换,%d表示用整数替换
%d 整数 %f 浮点数 %s 字符串 %x 十六进制整数

>>> 'hello, %s'%'world'
'hello, world'
>>> 'Hi, %s your age is %d'%('Limng',20)
'Hi, Limng your age is 20'

.format的用法比较灵活,参数的顺序和格式化的顺序不必完全相同

>>> name = 'Liming'
>>> age = 20
>>> print('age is {1},my name is {0}'.format(name,age))
age is 20,my name is Liming

本文地址:https://blog.csdn.net/qq_44969473/article/details/107577207

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网