Python学习之路 - String字符串

183 阅读1分钟

学习任何编程语言,在编程的过程中常常用到的一定是字符串【string】类型!字符串也是最基本数据类型。

如何创建字符串

在Python中可以用单引号或者双引号来创建字符串

singleString = 'Hello Python!'
doubleString = "Hello Python!"

还可以用三引号来多行创建字符串

threeString = '''
    hello world!
    hello python!
'''

除了直接用字面值创建字符串之外,还可以用数字类型创建字符串

number = 1234567890
numberString = str(number)

常用的字符串操作

直接对字符串使用upper()和lower()方法转换字符串的大小写

upperStr = "hello world!"
upperStr.upper()  # HELLO WORLD!

lowerStr = "HELLO WORLD!"
lowerStr.lower()  # hello world!

对字符串首字符进行大写转换

welcome = "hello world!"
print(welcome.strip()) # Hello World!

用加号直接拼接两个字符串组成一个新的字符串

str1 = 'hello '
str2 = 'world!'
addString = str1 + str2

字符串截取

welcome = "hello world"
welcome[0]  # h
welcome[2:5]  #  2..< 5  lo wo