字符串转义
转义符 "\"
转义字符串的意义在于将一些有特殊含义的字符标识为普通字符,在函数解析字符串时看到转义字符,就不再对其做做特殊处理,而是当做普通字符打印。
当反斜杠"\"位于行尾时,意味着换行。(一般只有在代码过长的情况下使用)
str = 'hello,' \
'world'
print(str)
>>> hello,world
如果反斜杠"\"所在的位置不是行尾,并且后接特殊字符时,则意味着"\"后面的特殊字符不做特殊处理。
print("Let\'s go!")
>>>Let's go!
print('\"Hello world!\" she said')
>>>"Hello world!" she said
print("\"Hello world!\" she said")
>>>"Hello world!" she said
如果要在代码中间进行换行可以使用 \n
str = 'hello,\nworld' print(str) >>> hello, >>> world
# 转义还有好多写法用于不同的功能 暂略。。。
字符串格式化
使用%格式化:要插入多个变量的话,必须使用元组。
info = "my name is %s . I'm %s ." % ('xxx', 18)
print(info)
>>> my name is xxx . I'm 18 .
如果要格式化的字符串和参数数量不同,则会抛出异常。
如果参数过多,代码可读性会变得很低。而且python官方文档不推荐使用%格式化字符串。
使用str.format()格式化字符串
str.format() 是对 %格式化 的改进,它使用普通函数调用语法,并且可以通过 __format__() 方法为对象进行扩展。
使用str.fromat()时,替换字段用大括号进行标记。
info = "my name is {}. I'm {}.I'm from{}." .format('xxx', 18, ['china'])
print(info)
>>> my name is xxx. I'm 18.I'm from['china'].
或者可以通过索引来以其他顺序引用变量
info = "I'm from{2}. My name is {0}. I'm {1}." .format('xxx', 18, ['china'])
print(info)
>>> I'm from['china']. My name is xxx. I'm 18.
还可以指定变量
info = "I'm from{country}. My name is {name}. I'm {age}." .format(name='xxx', age=18, country=['china'])
print(info)
>>>I'm from['china']. My name is xxx. I'm 18.
从字典中读取数据时还可以使用**
info = {'name': 'xxx', 'age': 18}
str = "my name is {name}. i'm {age}"
print(str.format(**info))
>>>my name is xxx. i'm 18
在处理多个参数和更长的字符串时,可读性依然很差。
f-strings
f-strings 是指以 f 或 F 开头的字符串,其中以 {} 包含的表达式会进行值替换。
name = 'xxx'
age = 18
print(f"my name is {name}, i'm {age}")
>>> my name is xxx, i'm 18
多行f-strings
name = 'xxx'
age = 18
country = 'china'
info = {
f"my name is {name}."
f"i'm {age}."
f"i'm from {country}."
}
print(info)
>>>{"my name is xxx.i'm 18.i'm from china."}
每行都要加上 f 前缀,否则格式化会不起作用。若字符串中包含括号 {},那么就需要用双括号包裹它。
可以用反斜杠进行转义字符,但是不能在 f-string 表达式中使用,#也不能出现在表达式中。
print(f"You are very \"handsome\"")
>>>You are very "handsome"
print(f"{You are very \"handsome\"}")
>>>SyntaxError: f-string expression part cannot include a backslash
字符串拼接
加号
a = 'hello' b = 'world' c = a + b print(c) >>> helloworld
逗号,有坑
a = 'hello'
b = 'world'
c = a, b
print(a, b)
>>> hello world
print(c)
>>> ('hello', 'world')
c是个元组
还有直连的,格式化,及字符串的join方法