python中str的方法详解

1.str(字符串)有什么功能?如何运用?

1.capitalize   2.casefold           3.center           4.count              5.encode
6.endswith     7.expandtabs         8.find             9.format             10.format_map
11.index       12.isalnum           13.isalpha         14.isascii           15.isdecimal
16.isdigit     17. isidentifier     18. islower        19.isnumeric         20.isprintable
21.isspace     22.istitle           23.isupper         24.join              25.ljust
26.lower       27.lstrip            28.partition       29.removeprefix      30.removesuffix
31.replace     32.rfind             33.rindex          34.rjust             35.rpartition
36.rsplit      37.rstrip            38.split           39.splitlines        40.startswith
41.strip       42.swapcase          43.title           44.translate         45.upper
46.zfill

2.capitalize:

 |  capitalize(self, /)

 |      Return a capitalized version of the string.

 |     

 |      More specifically, make the first character have upper case and the rest lower

 |      case.

 | 

代码:

str_data = 'hello'
str_date = str_data.capitalize()    # 字符串中首字母变成大写。
print(str_date)

运行结果:

Hello

3.casefold:

|  casefold(self, /)

|      Return a version of the string suitable for caseless comparisons.

 代码:

str_data = 'HELLO'
str_date = str_data.casefold()  # 无大小写区分比较版本的字符串
print(str_date)

运行结果:

hello

4. center:

 |  center(self, width, fillchar=' ', /)

 |      Return a centered string of length width.

 |     

 |      Padding is done using the specified fill character (default is a space).

 | 

代码:

str_data = 'hello'
str_date = str_data.center(20, '*')     # 居中对齐
print(str_date)

运行结果:

*******hello********

5.count:

 |  count(...)

 |      S.count(sub[, start[, end]]) -> int

 |     

 |      Return the number of non-overlapping occurrences of substring sub in

 |      string S[start:end].  Optional arguments start and end are

 |      interpreted as in slice notation.

 | 

 代码:

str_data = 'abcdef'
print(str_data.count('ab'))

运行结果:

1

6.encode:

 |  encode(self, /, encoding='utf-8', errors='strict')

 |      Encode the string using the codec registered for encoding.

 |     

 |      encoding

 |        The encoding in which to encode the string.

 |      errors

 |        The error handling scheme to use for encoding errors.

 |        The default is 'strict' meaning that encoding errors raise a

 |        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and

 |        'xmlcharrefreplace' as well as any other name registered with

 |        codecs.register_error that can handle UnicodeEncodeErrors.

 | 

 代码:

str_data = '你好'
str_date = str_data.encode()    # 编码 -> 将字符串编成字节
print(str_date, type(str_date))

运行结果:

b'\xe4\xbd\xa0\xe5\xa5\xbd' <class 'bytes'>

7.endswith:

 |  endswith(...)

 |      S.endswith(suffix[, start[, end]]) -> bool

 |     

 |      Return True if S ends with the specified suffix(后缀), False otherwise.

 |      With optional start, test S beginning at that position.

 |      With optional end, stop comparing S at that position.

 |      suffix can also be a tuple of strings to try.

 | 

 代码:

str_data = 'hello'
print(str_data.endswith('h''o'))

 运行结果:

False

8.expandtabs:

 |  expandtabs(self, /, tabsize(制表符大小)=8)

 |      Return a copy where all tab characters are expanded using spaces.

 |     

 |      If tabsize is not given, a tab size of 8 characters is assumed.

 | 

 代码:

str_data = 'hello'
print(str_data.expandtabs())

运行结果:

hello

9.find:

 |  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.

 | 

代码:

str_data1 = 'abcdef'
print(str_data1.find('abc'))

运行结果:

0

10.format(格式化):

 |  format(...)

 |      S.format(*args, **kwargs) -> str

 |     

 |      Return a formatted version of S, using substitutions from args and kwargs.

 |      The substitutions are identified by braces ('{' and '}').

 | 

代码1:

stu_list = [{'name': '张三', 'age': 18, 'gender': 'male'},
            {'name': '李四', 'age': 20, 'gender': 'male'},
            {'name': '王五', 'age': 22, 'gender': 'female'}]
print(f"{'name':^30}{'age':^10}{'gender':^10}")
for stu in stu_list:
    print(f"{stu['name']:^30}{stu['age']:^10}{stu['gender']:^10}")

代码2:

stu_list = [{'name': '张三', 'age': 18, 'gender': 'male'},
            {'name': '李四', 'age': 20, 'gender': 'male'},
            {'name': '王五', 'age': 22, 'gender': 'female'}]
print(f"{'name':^30}{'age':^10}{'gender':^10}")
print(f"{stu_list[0]['name']:^30}{stu_list[0]['age']:^10}{stu_list[0]['gender']:^10}")
print(f"{stu_list[1]['name']:^30}{stu_list[1]['age']:^10}{stu_list[1]['gender']:^10}")
print(f"{stu_list[2]['name']:^30}{stu_list[2]['age']:^10}{stu_list[2]['gender']:^10}")

代码3:

stu_list = [{'name': '张三', 'age': 18, 'gender': 'male'},
            {'name': '李四', 'age': 20, 'gender': 'male'},
            {'name': '王五', 'age': 22, 'gender': 'female'}]
print(f"{'name':^30}{'age':^10}{'gender':^10}")

     剩下的有时间会补上,或者去看看别人是如何使用这些命令的。

  • 16
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
当您需要将变量插入到字符串时,您可以使用Python的字符串格式化方法 `str.format()`。以下是一些用法示例: 1. 基本用法 您可以使用一对大括号 `{}` 来表示需要插入变量的位置,然后通过 `str.format()` 方法将变量传递进去。例如: ```python name = 'Alice' age = 25 print('My name is {}, and I am {} years old.'.format(name, age)) ``` 输出结果为:`My name is Alice, and I am 25 years old.` 2. 指定变量位置 如果您希望在字符串指定变量的位置,您可以在大括号内指定变量的索引位置。例如: ```python name = 'Alice' age = 25 print('My name is {0}, and I am {1} years old.'.format(name, age)) ``` 输出结果为:`My name is Alice, and I am 25 years old.` 3. 使用变量名称 如果您希望在字符串使用变量的名称而不是位置,您可以在大括号内指定变量的名称。例如: ```python name = 'Alice' age = 25 print('My name is {n}, and I am {a} years old.'.format(n=name, a=age)) ``` 输出结果为:`My name is Alice, and I am 25 years old.` 4. 格式化数字 您可以使用不同的格式指定符号来格式化数字,例如指定小数点后的位数,使用千位分隔符等等。例如: ```python x = 123.456 print('The value of x is {:.2f}'.format(x)) # 保留两位小数 print('The value of x is {:,}'.format(x)) # 添加千位分隔符 ``` 输出结果为:`The value of x is 123.46` 和 `The value of x is 123.456` 以上是 `str.format()` 方法的一些常见用法,希望对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值