Python程序检查字符串是否是回文

What is palindrome string?

什么是回文字符串?

A string is a palindrome if the string read from left to right is equal to the string read from right to left i.e. if the actual string is equal to the reversed string.

如果从左至右读取的字符串等于从右至左读取的字符串,即实际字符串等于反向字符串,则该字符串为回文

In the below program, we are implementing a python program to check whether a string is a palindrome or not?

在下面的程序中,我们正在实现一个python程序来检查字符串是否是回文?

Steps:

脚步:

  • First, find the reverse string

    首先,找到反向字符串

  • Compare whether revers string is equal to the actual string

    比较反转字符串是否等于实际字符串

  • If both are the same, then the string is a palindrome, otherwise, the string is not a palindrome.

    如果两者相同,则该字符串是回文,否则,该字符串不是回文。

Example:

例:

    Input: 
    "Google"
    Output:
    "Google" is not a palindrome string

    Input:
    "RADAR"
    Output:
    "RADAR" is a palindrome string

Method 1: Manual

方法1:手动

# Python program to check if a string is 
# palindrome or not

# function to check palindrome string
def isPalindrome(string):
  result = True
  str_len = len(string)
  half_len= int(str_len/2)

  for i in range(0, half_len):
    # you need to check only half of the string
    if string[i] != string[str_len-i-1]:
      result = False
    break
  
  return result 

# Main code
x = "Google"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")  

x = "ABCDCBA"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")

x = "RADAR"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string") 

Output

输出量

Google is not a palindrome string
ABCDCBA is a palindrome string
RADAR is a palindrome string

Method 2: Slicing

方法2:切片

# Python program to check if a string is 
# palindrome or not

# function to check palindrome string
def isPalindrome(string):
  rev_string = string[::-1]
  return string == rev_string

# Main code
x = "Google"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")  

x = "ABCDCBA"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")

x = "RADAR"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")  

Output

输出量

Google is not a palindrome string
ABCDCBA is a palindrome string
RADAR is a palindrome string


翻译自: https://www.includehelp.com/python/program-to-check-if-a-string-is-palindrome-or-not.aspx

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值