# 字符串基本用法
what_he_does = ' plays'
his_instrument = ' guitar'
his_name = 'Robert Johnson'
artist_intro = his_name + what_he_does + his_instrument
print(artist_intro)
打印结果:
Robert Johnson plays guitar
# 执行该代码段会报错
num = 1
string = '1'
print(num + string)
"""
因为字符串string只是python的一种数据类型,另一种数据类型为整数(integer),不同的数据类型不能进行合并,可以通过一些方法得到转换。
"""
执行结果:
Traceback (most recent call last):
File "C:/Users/issuser/PycharmProjects/untitled/test001/字符串操作.py", line 13, in <module>
print(num + string)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
# 转换数据类型:将字符串转换为整数
num = 1
string = '1'
num2 = int(string)
print(num + num2)
"""当不知道变量是什么类型的时候,可以用type()函数来查看"""
print(type(num2))
打印结果:
2
# 字符串间相乘
word = 'word'*3
print(word)
打印结果:
wordwordword
word = 'a loooooong word'
num = 12
string='Bang'
total='Bang' * (len(word)-12)
"""#等价于字符串'bang!'*4"""
print(total)
打印结果:
BangBangBangBang