python - 需要更优雅的解决方案来均匀字符串长度

标签 python string string-length

这是我得到的任务:

给定偶数长度的字符串,返回前半部分。所以字符串“WooHoo”会产生“Woo”。

first_half('WooHoo') → 'Woo'
first_half('HelloThere') → 'Hello'
first_half('abcdef') → 'abc'

这是我的解决方案:

def first_half(str):
    if len(str) % 2 == 0:
        b = len(str) // 2
        return str[:b]

我的问题是:

你能向我展示一个更简单的 Python 解决方案吗?当然,它不需要我使用变量来表示字符串长度的一半 (b)?

最佳答案

在Python中:

str = "WooHoo"   
str = str[:-len(str)/2]

关于python - 需要更优雅的解决方案来均匀字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31231856/

相关文章:

java - 输出文本文件中最长的单词

javascript - 使用循环将两个字符串字符排列成一个字符串

javascript - 来自字符串函数的图像

string - Lua 的 string.format 的转义字符串

javascript - 将字符串分成两部分,长度几乎相同

python - 如何使用 PyMongo 在 python 中执行通配符搜索 mongoDB

python - 间隔符号?

python - Pandas 数据框用索引填充空值

python - 数据帧到字典的问题,而单个键中有多个值

node.js - fs.readFile().toString 以空字符串终止