【问题标题】: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)
我需要创建一个长度相同的 *(星号)字符串。
我可以想到以下两种技巧:
- 计算字符串的长度,使用for循环创建长度相同的字符串
- 获取字符串的副本,并将每个字符替换为
*(星号)
您还有其他想法吗?
最快的方法是什么?
【问题讨论】:
标签:
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)))
如果你试一试,你可以看到*的字符串和行长度完全一样。