Python学习笔记(一)—— 字符串

(1)在python中,字符串可以用双引号或单引号括起来。例如:

str1 = "This is a string."
str2 = 'This is also a string.'
print (str1)
print (str2)

注意:双引号中可以包含单引号,单引号中也可以包含双引号。如:

str1 = 'I told my friend, "Python is my favorate language!"'
str2 = "It's beautiful"

(2)修改字符串的大小写。

name = "ada's Face"
print (name.upper())		#upper()函数将字符串改为大写
print (name.lower())		#lower()函数将字符串改为小写
print (name.title())		#title()函数将每个单词的首字母改为大写

输出结果为:

ADA'S FACE
ada's face
Ada'S Face

(3)合并字符串,使用“+”连接。

first_str = "hello"
last_str = "world"
print (first_str+" "+last_str)        #pyhton中使用加号(+)合并字符串

输出结果为:

hello world

(4)删除字符串中的空白。

test_str = ' python  '
do_str1 = test_str.rstrip()			#rstrip()函数去除字符串末尾的空白
do_str2 = test_str.lstrip()			#lstrip()函数去除字符串开头的空白
do_str3 = test_str.strip()			#strip()函数同时去除字符串两端的空白
print (do_str1)		
print (do_str2)		
print (do_str3)	

输出结果为:

 python
python  
python

(5)使用str()函数将非字符串值表示为字符串。

age = 23
message = "happy "+str(age)+"rd Birthday!"		#str()函数将非字符串值表示为字符串
print (message)

输出结果为:

happy 23rd Birthday!


扫描二维码关注公众号,回复: 4972042 查看本文章

猜你喜欢

转载自blog.csdn.net/ceo7820520/article/details/80100229