python - 在字符串中使用 len()

标签 python string

如何在不使用变量的情况下找到以下字符串的长度?

string = "This is a sentence and it has %d characters" % len(string)

print string

这个不行。正确的编码方式是什么?

最佳答案

在你的句子中,你试图在分配任何值之前评估字符串长度

string = "This is a sentence and it has %d characters" % len(string)

您应该考虑在哪里可以做到这一点,即:

 string = "%d chars.." 

可以同样扩展为

 string = "9 chars.." 

致:

 string = "10 chars.."

关于python - 在字符串中使用 len(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21982063/

相关文章:

python - 如何使用Python提取值(value)?

java - ClassCastException : java. lang.String 无法转换为 Ljava.lang.String

string - Swift String 编码和 NSXMLParser 解析问题

c - C语言中可以修改char字符串吗?

python - 如何将Python字节字符串表示形式转换为字节?

python - shutil.rmtree 删除只读文件

python - Pandas 的性能问题和日期时间列的过滤

python - 对不同的图像进行分类

python - 如何在新行字符上拆分 Python 字符串

string - 将 Vec 打印为字符串的惯用方法是什么?