在Python中打印包含数字的字符串的反写

A function is the collection of code that creates to perform a specific task and work for various inputs. When we have to do the same work after an interval then the function reduces the length of code, time complexity, etc. Here, we will write a function in Python that takes as input a positive integer which will be given by the user and returns the integer obtained by reversing the digits. Before going to solve this problem, we will learn a little bit about the function and how to create it in the Python programming language.

函数是创建代码以执行特定任务并为各种输入工作的代码集合。 当我们必须在间隔后执行相同的工作时,该函数将减少代码的长度,时间复杂度等。在这里,我们将使用Python编写一个函数,该函数将由用户给定的正整数作为输入并返回通过反转数字获得的整数 。 在解决此问题之前,我们将学习一些有关该函数以及如何使用Python编程语言创建它的知识。

Syntax to create a function in Python:

在Python中创建函数的语法:

    # definition
    def function_name(parameters):
	    ''' function statement that specifies the work 
	    of the function i.e body of function.'''
	    return(expression)

    # function calling
    print(functionname(parameters)

The function block begins with the "def" keyword and "function_name". In the parenthesis, it may have an argument or not.

功能块以“ def”关键字和“ function_name”开头。 在括号中,可以带或不带参数。

Now, let's start to create a function in Python that returns the integer obtained by reversing the digits. Before going to solve the above problem, assume the name of a function is the reverse(n) and the parameter n which value will be provided by the user. The function reverse(n) returns the integer obtained by reversing the digits in n.

现在,让我们开始在Python中创建一个函数,该函数返回通过反转数字获得的整数。 在解决上述问题之前,假定函数的名称为reverse(n) ,参数n为用户提供的值。 函数reverse(n)返回通过反转n中的数字获得的整数。

Program:

程序:

# function definition that will return 
# reverse string/digits 
def reverse(n):
    # to convert the integer value into string
    s=str(n) 
    p=s[::-1]
    return p 

# now, input an integer number
num = int(input('Enter a positive value: '))

# Calling the function and printing the result 
print('The reverse integer:',reverse(num))

Output

输出量

RUN 1:
Enter a positive value: 123456
The reverse integer: 654321

RUN 2:
Enter a positive value: 362435
The reverse integer: 534263

In Python, [::-1] is used to reverse list, string, etc. It is a property of slicing of the list.

在Python中, [::-1]用于反转列表,字符串等 。 它是列表切片的属性。

By using the above code, we can reverse a string that contains only digits, to practice more programs, visit – python programs.

通过使用上面的代码,我们可以反转仅包含数字的字符串,以练习更多程序,请访问– python program

翻译自: https://www.includehelp.com/python/print-the-reverse-of-a-string-that-contains-digits.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值