【问题标题】:How can I obtain a string of characters of the same length of another string? [duplicate]如何获得与另一个字符串长度相同的字符串? [复制]
【发布时间】:2021-07-01 12:11:57
【问题描述】:

假设,我有一个字符串

ContactMap(const core::data::structural::Structure &structure, double cutoff_distance, core::data::structural::selectors::AtomSelector_SP atoms_in_contact=nullptr)

我需要创建一个长度相同的 *(星号)字符串。

我可以想到以下两种技巧:

  1. 计算字符串的长度,使用for循环创建长度相同的字符串
  2. 获取字符串的副本,并将每个字符替换为 *(星号)

您还有其他想法吗?

最快的方法是什么?

【问题讨论】:

  • '*' * len(mystr)

标签: python string replace character


【解决方案1】:

幸运的是,Python 允许将字符串和整数相乘:

string = 'abc'
print('*' * len(string))

输出

***

【讨论】:

    【解决方案2】:

    你可以用这个:

    string = "ContactMap(const core::data::structural::Structure &structure, double cutoff_distance, core::data::structural::selectors::AtomSelector_SP atoms_in_contact=nullptr)"
    print(string)
    print("*" * (len(string)))
    

    如果你试一试,你可以看到*的字符串和行长度完全一样。

    【讨论】:

      猜你喜欢
      • 2016-07-06
      • 2015-03-12
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      • 2017-08-05
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多