#author("2023-09-27T10:13:40+08:00","default:Admin","Admin")
#author("2023-11-10T19:39:20+08:00","default:Admin","Admin")
[[Python]]

&color(red){※This article is based on Python 3.7.3};

#contents

* 类型转换 [#a40a760b]

** int() [#nde17a90]

可以将字符串转换为整数

#codeprettify{{
>>> num_str = '100'
>>> num_int = int(num_str)
>>> print(num_int)
100
}}

float将字符串转换为浮点数

* startswith [#h76341d8]

#codeprettify{{
s = 'hello good boy doiido'
if s.startswith('hel'):
  print("r")
else:
  print("w")
}}

* 截取 [#q79010d9]

没有类似 substr() 或 subString() 的方法。不过可以用 string[ indexA: indexB ] 来截取字符串。

#codeprettify{{
str = "this is a string example";
print( str[ 0: 4 ] );   # 截取 第 0 位到第 4 位的字符,打印 this
}}

* trim [#a78839eb]

Python中没有内置trim()函数,以下是一个自定义的trim()函数的实现:

#codeprettify{{
def trim(str):
    # 计算左侧和右侧需要删除的字符数
    left = 0
    right = len(str) - 1
    while (left < right) and (str[left] == ' '):
        left += 1
    while (right > left) and (str[right] == ' '):
        right -= 1
    return str[left:right+1]
}}
* isspace [#le7e2855]

判断是否字符串全部是空格

 if username.isspace() or password.isspace():  #判断输入的用户名或密码是否为空
    print('用户名或密码不能为空')
* 包含 [#f10a9798]

** in [#iaeec0c6]

#codeprettify{{
if findString in sourceString:
  return True
else:
  return False
}}

** find [#r97f1b69]

#codeprettify{{
if sourceString.find(findString) != -1:
  return True
else:
  return False
}}

* 正则表达式 [#i51843ce]

#codeprettify{{
import re
s1 ='我12345abcde'
s2 = 12345abcde'
#pattern字符串前加“r”表示原生字符串
pattern= re.compile(r"\w")

resultl = re.match(pattern, s1)
result2 = re.match(pattern, s2)

print(result1)
print(result2)
}}

#hr();
コメント:
#comment_kcaptcha

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS