我目前正在这样做:
teststring = "abc-def-ghi-jkl"
pos = teststring.find('-')
newstr = "{}-{}".format(teststring[0:pos], teststring[pos + 1:].replace('-', '_'))
这看起来不必要地笨拙。有没有更Pythonic的方法来做到这一点?
最佳答案
您可以使用str.split
:
pre, post = teststring.split('-', 1)
newstr = pre + '-' + post.replace('-', '_')
与您最初的解决方案一样,这仅在字符串中至少有一个 -
时才有效。您可以使用可变长度参数解包来解决此问题:
*pre, post = 'asdfd--saf'.split('-', 1)
newstr = '-'.join(pre + [post.replace('-', '_')])
现在 pre
将是前缀,如果没有破折号,则为空列表。 post
始终是完整后缀,带或不带破折号。
关于python - 在字符串中第一次出现后替换所有出现的字符的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68384562/