Python 字符串

python中的字符串用单引号或双引号括起来。

'hello'"hello"相同。

您可以使用以下函数显示字符串文字print()

print("Hello")
print('Hello')

字符串长度

要获取字符串的长度,请使用该len()函数。

a = "Hello, World!"
print(len(a))

检查字符串

要检查字符串中是否存在某个短语或字符,我们可以使用关键字 in

txt = "The best things in life are free!"
print("free" in txt)
txt = "The best things in life are free!"
print("expensive" not in txt)

切片

您可以使用切片语法返回一系列字符。

b = "Hello, World!"
print(b[2:5])
b[:5]
#从头开始切片
b[2:]
#切片到最后

大写

upper()方法以大写形式返回字符串:

a = "Hello, World!"
print(a.upper())
print(a.lower())

删除空格

空白是实际文本之前和/或之后的空格,并且您通常希望删除此空格。

print(a.strip()) 

替换字符串

print(a.replace("H", "J"))

拆分字符串

split()方法返回一个列表,其中指定分隔符之间的文本成为列表项。

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

字符串连接

要连接或组合两个字符串,您可以使用 + 运算符。

a = "Hello"
b = "World"
c = a + b
print(c)

字符串格式

正如我们在 Python 变量一章中学到的,我们不能像这样组合字符串和数字:(会报错)

age = 36
txt = "My name is John, I am " + age
print(txt)

但是我们可以通过使用方法来组合字符串和数字format()

format()方法接受传递的参数,格式化它们,并将它们放在占位符所在的字符串中 {}

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

 format() 方法接受无限数量的参数,并放置在相应的占位符中:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

转义字符

要在字符串中插入非法字符,请使用转义字符。

转义字符是一个反斜杠\,后跟要插入的字符。

非法字符的一个示例是字符串中的双引号被双引号括起来:

txt = "We are the so-called \"Vikings\" from the north."

 

https://www.w3schools.com/python/python_strings.asp

posted on 2022-03-26 11:22  -G  阅读(50)  评论(0)    收藏  举报

导航