# 字符串

# 如何分割字符串? | How to split a string?

txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(", ")
print(x)
1
2
3

# 如何提取字符串中的数字? | How to extract numbers in a string?

import re
s = '1x100.csv'
re.findall('\d+',s)
1
2
3

# 如何将字符串列表按数字大小排序?| How to sort string list by number?

参考 (opens new window)

import re

def atof(text):
    try:
        retval = float(text)
    except ValueError:
        retval = text
    return retval

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    float regex comes from https://stackoverflow.com/a/12643073/190597
    '''
    return [ atof(c) for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text) ]

alist=[
    "something1",
    "something2",
    "something1.0",
    "something1.25",
    "something1.105"]

alist.sort(key=natural_keys)
print(alist)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 如何选出两个字符中间的部分?|How to select the string between two strings?

>>> import re
>>> s = 'Part 1. Part 2. Part 3 then more text'
>>> re.search(r'Part 1\.(.*?)Part 3', s).group(1)
' Part 2. '
>>> re.search(r'Part 1(.*?)Part 3', s).group(1)
'. Part 2. '
1
2
3
4
5
6

# 如何控制浮点数的输出格式? | How to control the output format of a float number?

"{0:.2f}".format(13.949999999999999)
1

# 如何得到现在的时间?

import time

def timeString():
    return time.strftime("%Y%m%d-%H%M%S")
1
2
3
4

调用上面的函数 timeString() 可以得到:

20201222-162651
1

这个简单的操作可以方便你对生成的文件命名,而不会覆盖掉原来的文件。

fileName = 'Hello_{}.jpg'.format(timeString())
1
In [4]: fileName = 'Hello_{}.jpg'.format(timeString())

In [5]: fileName
Out[5]: 'Hello_20201222-163104.jpg'

In [6]: fileName = 'Hello_{}.jpg'.format(timeString())

In [7]: fileName
Out[7]: 'Hello_20201222-163115.jpg'
1
2
3
4
5
6
7
8
9

是不是挺酷的。

上次更新: 12/22/2020, 4:46:11 PM