1 版本查看
C:\Users\user>python --version
Python 3.10.1
C:\Users\user>python
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec 6 2021, 19:10:37) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello,phython!")
Hello,phython!
2 变量
2.1 字符(串)型变量
2.1.1 字符(串)型变量
message='hello,This is my first code.' #单引号或双引号引用起来的内容
print(message)
运行结果:
hello,This is my first code.
2.1.2 字符串操作
(1)大小写
name='josome liu'
print(name.upper()) #全部转为大写
print(name.lower())#全部转为小写
print(name.title())#首个字符大写
运行结果:
JOSOME LIU
josome liu
Josome Liu
(2) 字符串合并
first_name='liu'
last_name='josome'
full_name=f'{first_name} {last_name}'#中间加个空格
print(full_name.title()) #首字母大写
full_name2=first_name+last_name
print(full_name2)
运行结果:
Liu Josome
liujosome
(3) 字符串切片
string = "Line1-abcdef Line2-abc Line3-ab Line4-abcd"
string_find='ine1'
print(string)
print(string.split())#切片所有单词
print(string.split(' ', 1))#仅切片一个
print(string.find(string_find,0,10))#从0(左)到10(右)的字符中找出string_find的位置,未找到返回-1
运行结果:
Line1-abcdef Line2-abc Line3-ab Line4-abcd
['Line1-abcdef', 'Line2-abc', 'Line3-ab', 'Line4-abcd']
['Line1-abcdef', 'Line2-abc Line3-ab Line4-abcd']
1
2.1.3 空白(空格,制表符,换行符)
(1)通过制表符(\t)或换行符(\n)添加空白。
message_hello='\n\tHello,\nmy\tgirl!'
print(message_hello)
运行结果:
” Hello,
my girl!“
(2)删除空白
message_hello=' Hello '
print(message_hello)
print(message_hello.lstrip())#删除左边空白
print(message_hello.rstrip())#删除右边空白
print(message_hello.strip())#删除两边空白
print(message_hello.count('l'))#计算字符出现的次数
运行结果
”Hello “
” Hello“
”Hello“
2
2.1.4 Python三引号(triple quotes)
保证字符串中如果含有转义字符比如\n,\t," 等,显示的还是二日HTML中的字符串,即所见即所得。
errHTML = '''
<HTML><HEAD><TITLE>
Friends CGI Demo</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window.history.back()"></FORM>
</BODY></HTML>
'''
print(errHTML)
运行结果
<HTML><HEAD><TITLE>
Friends CGI Demo</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window.history.back()"></FORM>
</BODY></HTML>
如果不带双引号:编译器会识别有误
关于字符的更多操作参考:
2.1.5 字符ASCII
print(ord('C'))#显示ASCII编码
print(ord('人'))#字符整数表示
print(chr(67))#ACSCII转换为字符
print(chr(20154))#ACSCII转换为字符
运行结果:
67
20154
C
人