python-str内置函数

本文介绍了Python中str内置函数的使用,包括查找类函数如find、index等,判断类函数如islower、isalpha,以及内容判断和操作类函数如startswith、endswith、format和strip等。特别强调了isalpha函数的注意事项和在数字判断中正则表达式的推荐使用。

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

str内置函数

  • 很多语言字符串使用string表示,python里面使用str表示
  • 字符串查找类,find,index,islower(判断小写)
  • find:查找字符串中是否包括一个字符串
  • index:跟find的唯一区别是index如果找不到会引发异常
  • rfind,lfind:从左开始查或者从右开始查
s = "Fen fen is very beautiful and Zou kexin is very fascinating"
s1 = "Fen fen"
# 返回第一次发现这个字符串的位置
s.find(s1)

s2 = "xiaofen"
# 返回-1表示没有找到
s.find(s2)
-1

注意区别

help(str.find)
Help on method_descriptor:

find(...)
    S.find(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.
help(str.index)
Help on method_descriptor:

index(...)
    S.index(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found, 
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Raises ValueError when the substring is not found.
# index 会报错或者引发异常
s.index(s2)
---------------------------------------------------------------------------

ValueError             
### Python 字符串内置函数及其用法 以下是 Python 中常用的字符串内置函数以及其具体功能和用法: #### 1. `find()` 函数 `find()` 方法用于查找子字符串在原字符串中的位置。如果找到,则返回第一个匹配项的索引;如果没有找到,则返回 `-1`。 ```python s = "hello world" result = s.find("world") # 返回 6 表示从第6位开始有匹配[^1] ``` #### 2. `index()` 函数 `index()` 类似于 `find()`,但它会在找不到子字符串时抛出异常而不是返回 `-1`。 ```python s = "hello world" try: result = s.index("world") # 找到则返回索引值 6 except ValueError: print("Substring not found") ``` #### 3. `split()` 函数 `split()` 将字符串按照指定分隔符拆分成多个部分并返回一个列表。 ```python text = "apple,banana,cherry" fruits = text.split(",") # ['apple', 'banana', 'cherry'][^1] ``` #### 4. `join()` 函数 `join()` 用于将序列中的元素以指定字符连接成一个新的字符串。 ```python words = ["hello", "world"] sentence = " ".join(words) # 输出 "hello world" ``` #### 5. `replace()` 函数 `replace()` 替换字符串中所有的旧子字符串为新子字符串。 ```python message = "hello world" new_message = message.replace("world", "Python") # hello Python ``` #### 6. `isdigit()` 函数 `isdigit()` 判断字符串是否只由数字组成。 ```python num_str = "12345" print(num_str.isdigit()) # True ``` #### 7. `isalpha()` 函数 `isalpha()` 检查字符串是否仅包含字母。 ```python alpha_str = "abcXYZ" print(alpha_str.isalpha()) # True ``` #### 8. `isspace()` 函数 `isspace()` 验证字符串是否全部为空白字符(如空格、制表符等)。 ```python space_str = " " print(space_str.isspace()) # True ``` #### 9. `strip()` 函数 `strip()` 移除字符串两端的空白字符或其他指定字符。 ```python str_with_spaces = " Hello World! " cleaned_str = str_with_spaces.strip() # "Hello World!" ``` #### 10. `count()` 函数 `count()` 统计某个子字符串在原始字符串中出现的次数。 ```python phrase = "how much wood would a woodchuck chuck" word_count = phrase.count("wood") # 2 ``` #### 11. `len()` 函数 虽然严格来说不是字符串的方法,但它是用来获取字符串长度的标准方式。 ```python string_length = len("example") # 7 ``` #### 12. `startswith()` 和 `endswith()` 函数 这两个方法分别验证字符串是否以特定前缀或后缀开头/结尾。 ```python url = "https://www.example.com" print(url.startswith("https")) # True print(url.endswith(".com")) # True ``` #### 13. `upper()` 和 `lower()` 函数 转换整个字符串为大写或小写字母形式。 ```python name = "Alice" uppercase_name = name.upper() # ALICE lowercase_name = uppercase_name.lower() # alice ``` #### 14. 映射替换 (`maketrans()` 和 `translate()`) 可以通过创建翻译表来实现更复杂的字符替换操作。 ```python trans_table = str.maketrans('abcdefg', '1234567') translated_text = "abc".translate(trans_table) # "123"[^2] ``` #### 15. 动态调用函数 (通过名称) 利用 `globals()` 或者 `locals()` 可以动态执行对应名字的函数。 ```python def add(a, b): return a + b func_name = "add" dynamic_func_call = globals()[func_name](1, 2) # 结果为 3[^3] ``` ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值