string #9
Replies: 7 comments
-
|
反转字符串 解决这个问题最简单的方法是使用切片,字符串的切片与列表的切片使用方法完全相同,可以参考在列表的切片一节中的详细介绍。程序如下: # 输入一个字符串
input_string = input("请输入一个字符串: ")
# 反转字符串
reversed_string = input_string[::-1]
# 输出反转后的字符串
print("反转后的字符串是:", reversed_string) |
Beta Was this translation helpful? Give feedback.
-
|
是否是回文 只要把字符串反转,在检查反转之后与原来是否相等即可: input_string = "abccba"
# 去除字符串中的空格并转换为小写
cleaned_string = input_string.replace(" ", "").lower()
# 检查字符串是否与其反转形式相同
print(cleaned_string == cleaned_string[::-1]) |
Beta Was this translation helpful? Give feedback.
-
|
首字母大写 input_string = "hello world!"
print(input_string.title()) |
Beta Was this translation helpful? Give feedback.
-
|
写的很棒 |
Beta Was this translation helpful? Give feedback.
-
整数所有位上数字的乘积# 输入一个整数
number = 6789
# 初始化乘积为 1
product = 1
# 对每一位数字进行乘积计算
for digit in str(number):
product *= int(digit) |
Beta Was this translation helpful? Give feedback.
-
变位词# 输入两个字符串
str1 = "eleven plus two"
str2 = "twelve plus one"
# 将字符串转为小写并排序后比较
print(sorted(str1.lower()) == sorted(str2.lower()))除了排序,这个问题也可以通过统计字符串中每个字母出现的次数的方法解决。 |
Beta Was this translation helpful? Give feedback.
-
最大相同字符长度def max_consecutive_length(s):
if not s:
return 0
max_len = 1
current_len = 1
current_char = s[0]
for char in s[1:]:
if char == current_char:
current_len += 1
else:
max_len = max(max_len, current_len)
current_char = char
current_len = 1
max_len = max(max_len, current_len)
return max_len
# 示例
s = "aaabbbbaa"
print(max_consecutive_length(s)) # 输出:4 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
string
字符串和列表的处理通常离不开循环、条件等结构。虽然本书为了集中讲解相关内容,首先介绍了字符串和列表的各种操作方法,但对于初学者来说,更好的学习方式可能是先大致了解一下字符串和列表是什么样的数据。等到学习了循环结构后,再回头来学习这两种数据的复杂操作方法,会更容易理解。
https://py.qizhen.xyz/string
Beta Was this translation helpful? Give feedback.
All reactions