计算机网络/计算机科学与应用/系统/运维/开发

Python【基础】字符串

# 字符串的常用操作

# 拼接字符串  “+”运算符可以连接多个字符串

mot_en = 'Remembrance is a form o fmeeting. Frgetfulness is a form of freedom.'
mot_cn = '记忆是一种相遇。遗忘是一种自由。'
# Remembrance is a form o fmeeting. Frgetfulness is a form of freedom.--记忆是一种相遇。遗忘是一种自由。
print(mot_en + '--' + mot_cn)


# 字符串不允许直接与其他类型数据拼接

str1 = '今天走了'
num = 12098
str2 = '步'
print(str1 + num + str2)

Traceback (most recent call last):
  File "E:/Python_stu/Python从入门到精通/字符串编码转换.py", line 18, in <module>
    print(str1 + num + str2)
TypeError: can only concatenate str (not "int") to str


# 使用str()函数将整数转换为字符串

str1 = '今天走了'
num = 12098
str2 = '步'
# 今天走了12098步
print(str1 + str(num) + str2)


#  计算字符串的长度 len(string) string用于指定要进行长度统计的字符串

str3 = '人生苦短,我用Python'
print(len(str3))  # 13


# 检索字符串

# count() 用于检索指定字符串在另一个字符串中出现的次数 如果检索的字符串不存在,则返回0;否则返回出现的次数。

# str.count(sub [,start [, end]])
str4 = '@明日科技 @PHP @MySQL'
# 字符串 @明日科技 @PHP @MySQL 中包括 3 个@符号
print('字符串', str4, '中包括', str4.count('@'), '个@符号')


python

泰山崩于前而色不变,麋鹿兴于左而目不瞬,然后可以制利害,可以待敌。--心术

评论

^