成语| 古诗大全| 扒知识| 扒知识繁体

当前位置:首页 > 趣味生活

python如何将字符转化为数字

Q1:python如何将字符串里有数字和文字怎么提取数字

从字符串“127米”中提取数字127:

方法一、利用正则表达式

用法:

##总结##^匹配字符串的开始。##$匹配字符串的结尾。##\b匹配一个单词的边界。##\d匹配任意数字。##\D匹配任意非数字字符。##x?匹配一个可选的x字符(换言之,它匹配1次或者0次x字符)。##x*匹配0次或者多次x字符。##x+匹配1次或者多次x字符。##x{n,m}匹配x字符,至少n次,至多m次。##(a|b|c)要么匹配a,要么匹配b,要么匹配c。##(x)一般情况下表示一个记忆组(rememberedgroup)。你可以利用re.search函数返回对象的groups()函数获取它的值。##正则表达式中的点号通常意味着“匹配任意单字符”

[plain]view plaincopy

importre

string=u127米

printre.findall(r"\d+\.?\d*",string)

方法二、利用filter(str.isdigit, iterable)

[plain]view plaincopy

string=u127米

print(filter(str.isdigit,string))

bug:TypeError: descriptor isdigit requires a str object but received a unicode

原因:string不是str类型

修改为:

[plain]view plaincopy

string=u127米

string2=string.encode(gbk)

print(type(str))

print(filter(str.isdigit,string2))

结果:


127、

注意:要提取的字符串不能命名为str,否则会出现TypeError: isdigit() takes no arguments (1 given)

因为str和filter里的str重名了。

Q2:python如何将list中的字符转为数字

python里面好像只能直接转一维的list,以python 3.6为例:

问题 1:

list=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

转化为:list=[0, 1 ,2, 3, 4, 5, 6, 7, 8, 9]

代码如下:

1list_to_float=list(map(lambdax:float(x),list))

问题2:(对于二维数组,需要加个循环,变成一维数组)

list=[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

转化为:list=[[0, 1 ,2], [3, 4, 5], [6, 7, 8]]

代码如下:

1234list_to_float=[]foreachinlist:each_line=list(map(lambdax:float(x),each))list_to_float.append(each_line)

总之:关键还是map函数映射,如果是python 2.x的话,你可以试试

1list_to_float=map(lambdax:float(x),list)

Q3:Python怎么将数字数组转为字符数组

用map函数

文档

map(function,iterable,...)

Applyfunctionto every item ofiterableand return a list of the results. If additionaliterablearguments are passed,functionmust take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended withNoneitems. IffunctionisNone, the identity function is assumed; if there are multiple arguments,map()returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). Theiterablearguments may be a sequence or any iterable object; the result is always a list.

12a=[1,2,3,4]s=map(str,a)

Q4:python如何给一段文本中的某些字符添加数字编号?

我是做前端的,对于python的问题回答的可能不会很准确

这里建议您试试下面这段代码:

猜你喜欢

更多