python——字符串与序列

字符串

python中没有字符的概念==与元组一样,不能直接修改

支持拼接版的修改

>>> str1='asdf'

>>> str1.capitalize()

'Asdf'

>>> str1

'asdf'

>>> str1='DSADas'

>>> str1.casefold()

'dsadas'

>>> str1

'DSADas'

>>> str1.center(40)

'                 DSADas                 '

>>> str1

'DSADas'

>>> str1.count('a')

1

>>> str1.count('a',true)

Traceback (most recent call last):

  File "<pyshell#9>", line 1, in <module>

    str1.count('a',true)

NameError: name 'true' is not defined

>>> str1.endwith(('s')

KeyboardInterrupt

>>> str1.endswith('s')

True

>>> str1='i\tlove\tprogoram'

>>> str1.expandtabs()

'i       love    progoram'

>>> str1.find('pro')

7

>>> str1.find('f')

-1

>>> str1.index('f')

Traceback (most recent call last):

  File "<pyshell#20>", line 1, in <module>

    str1.index('f')

ValueError: substring not found

>>> str1.index('pro')

7

isalnum()=isalpha()+isdigit()

>>> str2='周雨佳'

>>> str2.islower()  至少包含一个区分大小写的字符,且这些字符都是小写,返回true

False

istitle()所有单词首字母都是大写,其他字母都是小写

isupper()所有字母都是大写

>>> str2.join('dsds')

'd周雨佳s周雨佳d周雨佳s'

>>> str3=' fdsfsd   sfds  '

>>> str3.lstrip()

'fdsfsd   sfds  '

>>> str3.rstrip()

' fdsfsd   sfds'

>>> str3.partition('ds')

(' f', 'ds', 'fsd   sfds  ')

>>> str3.replace('f','z',2)

' zdszsd   sfds  '

rfind rindex rstrip startswith strip一样的

>>> str3.split('')

Traceback (most recent call last):

  File "<pyshell#30>", line 1, in <module>

    str3.split('')

ValueError: empty separator

>>> str3.split()

['fdsfsd', 'sfds']

>>> str3

' fdsfsd   sfds  '

>>> str3.strip('s')

' fdsfsd   sfds  '

>>> str4='FFSDds'

>>> str4.swap()

Traceback (most recent call last):

  File "<pyshell#35>", line 1, in <module>

    str4.swap()

AttributeError: 'str' object has no attribute 'swap'

>>> str3.title()

' Fdsfsd   Sfds  '

>>> str3.translate(str.maketrans('s','z'))

' fdzfzd   zfdz  '

>>> str3.maketrans('s','z')

{115: 122}

>>> str3.zfill(30)

'00000000000000 fdsfsd   sfds  '



格式化字符串

>>> str1='asdf'

>>> str1.capitalize()

'Asdf'

>>> str1

'asdf'

>>> str1='DSADas'

>>> str1.casefold()

'dsadas'

>>> str1

'DSADas'

>>> str1.center(40)

'                 DSADas                 '

>>> str1

'DSADas'

>>> str1.count('a')

1

>>> str1.count('a',true)

Traceback (most recent call last):

  File "<pyshell#9>", line 1, in <module>

    str1.count('a',true)

NameError: name 'true' is not defined

>>> str1.endwith(('s')

KeyboardInterrupt

>>> str1.endswith('s')

True

>>> str1='i\tlove\tprogoram'

>>> str1.expandtabs()

'i       love    progoram'

>>> str1.find('pro')

7

>>> str1.find('f')

-1

>>> str1.index('f')

Traceback (most recent call last):

  File "<pyshell#20>", line 1, in <module>

    str1.index('f')

ValueError: substring not found

>>> str1.index('pro')

7

>>> str2='周雨佳'

>>> str2.islower()

False

>>> str2.join('dsds')

'd周雨佳s周雨佳d周雨佳s'

>>> str3=' fdsfsd   sfds  '

>>> str3.lstrip()

'fdsfsd   sfds  '

>>> str3.rstrip()

' fdsfsd   sfds'

>>> str3.partition('ds')

(' f', 'ds', 'fsd   sfds  ')

>>> str3.replace('f','z',2)

' zdszsd   sfds  '

>>> str3.split('')

Traceback (most recent call last):

  File "<pyshell#30>", line 1, in <module>

    str3.split('')

ValueError: empty separator

>>> str3.split()

['fdsfsd', 'sfds']

>>> str3

' fdsfsd   sfds  '

>>> str3.strip('s')

' fdsfsd   sfds  '

>>> str4='FFSDds'

>>> str4.swap()

Traceback (most recent call last):

  File "<pyshell#35>", line 1, in <module>

    str4.swap()

AttributeError: 'str' object has no attribute 'swap'

>>> str3.title()

' Fdsfsd   Sfds  '

>>> str3.translate(str.maketrans('s','z'))

' fdzfzd   zfdz  '

>>> str3.maketrans('s','z')

{115: 122}

>>> str3.zfill(30)

'00000000000000 fdsfsd   sfds  '

>>> "{0} love{1}.{2}".format("i","am",'misszhou')

'i loveam.misszhou'

>>> "{a}{b}{c}".format(a="i",b="am",c="misszhou")

'iammisszhou'

>>> "{a}{b}{0}".format(a="i",b="am","misszhou")

SyntaxError: positional argument follows keyword argument

>>> print('\tz')

z

>>> "{{0}}".format("no")

'{0}'

>>> '{0:.lf}{1}'.format(27.2324,'GB')

Traceback (most recent call last):

  File "<pyshell#45>", line 1, in <module>

    '{0:.lf}{1}'.format(27.2324,'GB')

ValueError: Format specifier missing precision

>>> '{0:.1f}{1}

SyntaxError: EOL while scanning string literal

>>> '{0:.1f}{1}'.format(27.2324,'GB')

'27.2GB'

 %c %s %d o x  X f e E g G(根据数字大小选择f e)

>>> '%c' %97

'a'

>>> '%c%c%c' % {97,98,99}

Traceback (most recent call last):

  File "<pyshell#49>", line 1, in <module>

    '%c%c%c' % {97,98,99}

TypeError: %c requires int or char

>>> '%c%c%c' % (97,98,99)

'abc'

>>> '%s' % 'jkfjdk'

'jkfjdk'

>>> '%d+%d=%d' % (4,5,4+5)

'4+5=9'

>>> '%o' % 12

'14'

>>> '%x' %10

'a'

>>> '%f" %23.43423

SyntaxError: EOL while scanning string literal

>>> '%f'%2343

'2343.000000'

>>> '%e'%342443r5r32

SyntaxError: invalid syntax

>>> '%e'%432434

'4.324340e+05'

格式化操作符辅助指令

>>> '%10d'%5

'         5'

>>> '%-10d'%4

'4         '

>>> '%+d'%4

'+4'

>>> '%+d'%-5

'-5'

>>> '%#o'%432

'0o660'

>>> '%#X'%4543

'0X11BF'

>>> '%#d'%4342

'4342'

>>> '%010d'%4342

'0000004342'

>>> '%-010d'%43543

'43543     '


转义字符也是一样用的

\t \n \r

序列

列表、元组、字符串的共同点

都可以通过索引得到每一个元素

默认索引值是0

可以通过分片的方法得到一个范围内的元素集合

有很多相同的操作符

list

>>> help(list)

Help on class list in module builtins:

class list(object)

 |  list() -> new empty list

 |  list(iterable) -> new list initialized from iterable's items

 |  (迭代:重复反馈过程的活动,目的通常是为了接近和达到所需的目标或结果,每次重复叫做迭代,每次迭代的结果作为下一次的初始值)

 |  Methods defined here:

 |  

 |  __add__(self, value, /)

 |      Return self+value.

 |  

 |  __contains__(self, key, /)

 |      Return key in self.

 |  

 |  __delitem__(self, key, /)

 |      Delete self[key].

 |  

 |  __eq__(self, value, /)

 |      Return self==value.

 |  

 |  __ge__(self, value, /)

 |      Return self>=value.

 |  

 |  __getattribute__(self, name, /)

 |      Return getattr(self, name).

 |  

 |  __getitem__(...)

 |      x.__getitem__(y) <==> x[y]

 |  

 |  __gt__(self, value, /)

 |      Return self>value.

 |  

 |  __iadd__(self, value, /)

 |      Implement self+=value.

 |  

 |  __imul__(self, value, /)

 |      Implement self*=value.

 |  

 |  __init__(self, /, *args, **kwargs)

 |      Initialize self.  See help(type(self)) for accurate signature.

 |  

 |  __iter__(self, /)

 |      Implement iter(self).

 |  

 |  __le__(self, value, /)

 |      Return self<=value.

 |  

 |  __len__(self, /)

 |      Return len(self).

 |  

 |  __lt__(self, value, /)

 |      Return self<value.

 |  

 |  __mul__(self, value, /)

 |      Return self*value.n

 |  

 |  __ne__(self, value, /)

 |      Return self!=value.

 |  

 |  __new__(*args, **kwargs) from builtins.type

 |      Create and return a new object.  See help(type) for accurate signature.

 |  

 |  __repr__(self, /)

 |      Return repr(self).

 |  

 |  __reversed__(...)

 |      L.__reversed__() -- return a reverse iterator over the list

 |  

 |  __rmul__(self, value, /)

 |      Return self*value.

 |  

 |  __setitem__(self, key, value, /)

 |      Set self[key] to value.

 |  

 |  __sizeof__(...)

 |      L.__sizeof__() -- size of L in memory, in bytes

 |  

 |  append(...)

 |      L.append(object) -> None -- append object to end

 |  

 |  clear(...)

 |      L.clear() -> None -- remove all items from L

 |  

 |  copy(...)

 |      L.copy() -> list -- a shallow copy of L

 |  

 |  count(...)

 |      L.count(value) -> integer -- return number of occurrences of value

 |  

 |  extend(...)

 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable

 |  

 |  index(...)

 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.

 |      Raises ValueError if the value is not present.

 |  

 |  insert(...)

 |      L.insert(index, object) -- insert object before index

 |  

 |  pop(...)

 |      L.pop([index]) -> item -- remove and return item at index (default last).

 |      Raises IndexError if list is empty or index is out of range.

 |  

 |  remove(...)

 |      L.remove(value) -> None -- remove first occurrence of value.

 |      Raises ValueError if the value is not present.

 |  

 |  reverse(...)

 |      L.reverse() -- reverse *IN PLACE*

 |  

 |  sort(...)

 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

 |  

 |  ----------------------------------------------------------------------

 |  Data and other attributes defined here:

 |  

 |  __hash__ = None

>>> a=list()

>>> a

[]

>>> b='i am misszhou'

>>> b=list(b)

>>> b

['i', ' ', 'a', 'm', ' ', 'm', 'i', 's', 's', 'z', 'h', 'o', 'u']

>>> c=(1,1,3,5,8)

>>> c=list(c)

>>> c

[1, 1, 3, 5, 8]

>>> help(tuple)

Help on class tuple in module builtins:

class tuple(object)

 |  tuple() -> empty tuple

 |  tuple(iterable) -> tuple initialized from iterable's items

 |  

 |  If the argument is a tuple, the return value is the same object.

 |  

 |  Methods defined here:

 |  

 |  __add__(self, value, /)

 |      Return self+value.

 |  

 |  __contains__(self, key, /)

 |      Return key in self.

 |  

 |  __eq__(self, value, /)

 |      Return self==value.

 |  

 |  __ge__(self, value, /)

 |      Return self>=value.

 |  

 |  __getattribute__(self, name, /)

 |      Return getattr(self, name).

 |  

 |  __getitem__(self, key, /)

 |      Return self[key].

 |  

 |  __getnewargs__(...)

 |  

 |  __gt__(self, value, /)

 |      Return self>value.

 |  

 |  __hash__(self, /)

 |      Return hash(self).

 |  

 |  __iter__(self, /)

 |      Implement iter(self).

 |  

 |  __le__(self, value, /)

 |      Return self<=value.

 |  

 |  __len__(self, /)

 |      Return len(self).

 |  

 |  __lt__(self, value, /)

 |      Return self<value.

 |  

 |  __mul__(self, value, /)

 |      Return self*value.n

 |  

 |  __ne__(self, value, /)

 |      Return self!=value.

 |  

 |  __new__(*args, **kwargs) from builtins.type

 |      Create and return a new object.  See help(type) for accurate signature.

 |  

 |  __repr__(self, /)

 |      Return repr(self).

 |  

 |  __rmul__(self, value, /)

 |      Return self*value.

 |  

 |  count(...)

 |      T.count(value) -> integer -- return number of occurrences of value

 |  

 |  index(...)

 |      T.index(value, [start, [stop]]) -> integer -- return first index of value.

 |      Raises ValueError if the value is not present.

>>> len(a)

0

>>> len(c)

5

>>> c

[1, 1, 3, 5, 8]

>>> max(c)

8

>>> max(b)

'z'

>>> numbers=[1,18,13,0,-23,4,-342]

>>> max(numbers)

18

>>> min(numbers)

-342

>>> chars='1232342'

>>> min(chars)

'1'

>>> tuple1=(1,2,4,5,7,9)


必须是相同类型的才有max min 数字和字符不能比较


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,Python 计算思维训练——字典和字符串(一)。 在Python中,字典(dictionary)是一种非常有用的数据结构,它可以存储键值对(key-value pairs),并且可以根据键快速地查找相应的值。字典的键必须是不可变的类型,比如字符串、整数或元组等,而值可以是任意类型。字典的语法使用花括号 {},并且键值对之间用冒号 : 分隔。 例如,下面的代码创建了一个简单的字典,其中包含了三个键值对。 ``` info = {'name': '张三', 'age': 18, 'gender': '男'} ``` 你可以通过以下方式访问字典中的值: ``` print(info['name']) # 输出:张三 print(info['age']) # 输出:18 print(info['gender']) # 输出:男 ``` 如果字典中不存在指定的键,则会抛出 KeyError 异常。你可以使用字典的 get() 方法来避免这种异常,该方法在键不存在时会返回一个默认值(默认值为 None)。 ``` print(info.get('address')) # 输出:None ``` 另外,你可以使用 in 关键字来检查一个键是否存在于字典中。 ``` print('name' in info) # 输出:True print('address' in info) # 输出:False ``` 除了创建字典,还可以通过字典推导式来创建字典。字典推导式的语法与列表推导式类似,只不过使用花括号 {} 来表示字典。 例如,下面的代码创建了一个简单的字典,其中包含了前五个自然数的平方。 ``` squares = {x: x**2 for x in range(1, 6)} print(squares) # 输出:{1: 1, 2: 4, 3: 9, 4: 16, 5: 25} ``` 接下来,我们来看一下字符串(string)的相关操作。字符串Python 中最常用的数据类型之一,它可以用来表示文本或字符序列Python中的字符串是不可变的,也就是说,一旦创建了一个字符串,就不能修改它的内容。 你可以使用单引号、双引号或三引号来创建一个字符串。如果字符串中包含了单引号或双引号,则需要使用转义字符 \ 来表示。 例如,下面的代码分别创建了三个字符串,分别使用了单引号、双引号和三引号。 ``` s1 = 'Hello, world!' s2 = "Python is awesome!" s3 = """This is a multi-line string that spans multiple lines.""" ``` Python中的字符串支持许多常用的操作,比如字符串拼接、字符串截取、字符串替换、字符串查找等等。在后面的训练中,我们会逐一介绍这些操作。 好了,以上就是本次的 Python 计算思维训练,主要介绍了字典和字符串的基本使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值