RHEL/Centos7.x/python-2.7 Example

本文深入讲解了Python的基础语法,包括字符串操作、整型与字符串转换、函数定义与使用,以及如何处理UTF-8编码的字符串。通过具体示例,读者可以了解到如何避免常见的类型错误,如何将整数转换为百分比字符串,以及如何从带有百分号的字符串中提取整数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

lake@localhost:~/Desktop$ python -V
Python 2.7.5
lake@localhost:~/Desktop$ python 
Python 2.7.5 (default, Oct 11 2015, 17:47:16) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

 

1. String 
>>> print("hello")
hello
>>> print hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'hello' is not defined
>>> print "hello"
hello
>>> 

2. Int/String 

>>> int_a = 2 
>>> print int_a
2
>>> print int_a+"hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> print str(int_a)+"hello"
2hello

 

3. Function 

######### translate int into a string with "%"

>>> def int_to_percent_string(int_para):
...         return str(int_para)+"%"           ####  ... is <tab> in text
... 
>>> print int_to_percent_string(22)
22%
>>> 
 

######### get a int number from a string like "xx%"

> def percent_to_int(string):
...     if "%" in string:
...         newint = int(string.strip("%")) 
...         return newint
...     else:
...         return int(0)
...         
... 
>>> print percent_to_int("22%")
22
>>> 

 

 

4. print utf8 string 

 

#-*- coding:UTF-8 -*-

string=xxxx   ### from uiautomator /device object attribute  .text
name=string.encode("utf-8")
print("Ascii puls utf-8 string "+name)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值