Python-变量

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>

如果不带双引号:编译器会识别有误

关于字符的更多操作参考:

Python 字符串 - Python 教程 - 自强学堂Python 字符串 字符串是最 Python 总常用的数据类型。我们可以使用引号来创建字符串。 创建字符串很简单,只要为变量分配一个值即可。例如: var1 = 'Hello World!' var2 = 'Python Programming' Python访问字符串中的值 Python不支持单字符类型,单字符也在Python也是作为一个字符串使用。 Python访问子字符串,可以使用..https://code.ziqiangxuetang.com/python/python-strings.html

2.1.5 字符ASCII

print(ord('C'))#显示ASCII编码
print(ord('人'))#字符整数表示
print(chr(67))#ACSCII转换为字符
print(chr(20154))#ACSCII转换为字符

运行结果:

67
20154
C

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值