setState
我想要这样:
myString = "I Am New To Python,
Trying to learn Different things.
Need your help in this Case."
我该怎么做?
答案 0 :(得分:1)
使用列表理解功能,
myString = '''I Am New To Python,
Trying to learn Different things.
Need your help in this Case.'''
modified_string = '\n'.join([i.strip()[0].lower()+i.strip()[1:] for i in myString.split('\n')])
希望这会有所帮助!干杯!
答案 1 :(得分:1)
与行中的第一个字符匹配并用小写字母替换的正则表达式替换非常简单:
import re
myString = '''I Am New To Python,
Trying to learn Different things.
Need your help in this Case.'''
print(re.sub(r'^(\s*.)',lambda m: m.group(1).lower(),myString,flags=re.MULTILINE))
输出:
i Am New To Python,
trying to learn Different things.
need your help in this Case.
请注意,您需要将字符串三引号有效。我在替换中加入了前导空白,因此结果将其删除。使用r'^\s*(.)'
将其保留。
替换是一个匿名函数,它接收正则表达式的match对象。
答案 2 :(得分:0)
如果您还不了解列表理解功能,那么对于初学者来说,这可能更容易理解。
myString = """I Am New To Python,
Trying to learn Different things.
Need your help in this Case."""
mystring1=myString.splitlines()
mystring2=""
for x in mystring1:
mystring2 = mystring2 + x[0].lower() + x[1:] +"\n"
print(mystring2)