仅打印字符串中的数字

2024-09-29 23:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图打印出字符串中的数字。由于某种原因,输出有点不正常

def get_numerals(string):
    for i in string:
        if i in "1234567890":
            print(i,end="")
        else:
            print("",end = "")
    return i

print(get_numerals("CS1301"))
print(get_numerals("Georgia Institute of Technology"))
print(get_numerals("8675309"))

输出:

13011
y
86753099

Tags: 字符串inforgetstringreturnifdef
3条回答
def get_numerals(string):
    return ''.join( [x for x in string if x.isdigit() ] )

无论是数字还是字符,都返回最后一个字符。您的版本的一个简单解决方法是:

def get_numerals(string):
    for i in string:
        if i.isdigit():  # isdigit() is more convenient to check whether the char is digit or not
            print(i, end="")
        else:
            print("", end = "")
    return ''

print(get_numerals("CS1301"))  # 1301
print(get_numerals("Georgia Institute of Technology")) # 
print(get_numerals("8675309")) # 8675309

或者您可以使用正则表达式:

import re   
def get_numerals(string):
    res = re.findall(r'\d+', string)  # finds positive digits
    # res = re.findall(r'-?\d+', string) # if you want negative and positive digts
    return "".join(res)


print(get_numerals("CS13011111"))  # 1301
print(get_numerals("Georgia Institute of Technology")) # 
print(get_numerals("8675309")) # 8675309

基本方法是:

def get_numerals(string):
    tempstr =""
    for i in string:
       
        if i.isdigit():
            tempstr=tempstr+i
       
    return tempstr

print(get_numerals("CS1301"))
print(get_numerals("Georgia Institute of Technology"))
print(get_numerals("8675309"))

输出:

1301

8675309

使用Regular expression还可以从字符串中获取数字

import re

def get_numerals(string):
    temp = re.findall(r'\d+', string) 
    res = list(map(int, temp)) 
    
    return res
    
print(get_numerals("CS1301"))
print(get_numerals("Georgia Institute of Technology"))
print(get_numerals("8675309"))

输出:

[1301]
[]
[8675309]

相关问题 更多 >

    热门问题