如何在Python中声明长字符串?

ifsvaxew  于 2023-03-21  发布在  Python
关注(0)|答案(5)|浏览(108)

我在Python中有一个很长的字符串:

long_string = '
this is a really
really
really
long
string
'

但是,由于字符串跨越多行,python无法将其识别为字符串。如何解决这个问题?

s3fp2yjn

s3fp2yjn1#

你也可以这样做,这很好,因为你可以更好地控制字符串中的空格:

long_string = (
    'Lorem ipsum dolor sit amet, consectetur adipisicing elit, '
    'sed do eiusmod tempor incididunt ut labore et dolore magna '
    'aliqua. Ut enim ad minim veniam, quis nostrud exercitation '
    'ullamco laboris nisi ut aliquip ex ea commodo consequat. '
    'Duis aute irure dolor in reprehenderit in voluptate velit '
    'esse cillum dolore eu fugiat nulla pariatur. Excepteur sint '
    'occaecat cupidatat non proident, sunt in culpa qui officia '
    'deserunt mollit anim id est laborum.'
)
u59ebvdq

u59ebvdq2#

long_string = '''
this is a really
really
really
long
string
'''

"""做同样的事情。

bvjxkvbb

bvjxkvbb3#

您可以使用其中一种

long_string = 'fooo' \
'this is really long' \
'string'

或者需要换行

long_string_that_has_linebreaks = '''foo
this is really long
'''
uz75evzq

uz75evzq4#

我也能让它像这样工作。

long_string = '\
this is a really \
really \
really \
long \
string\
'

我在网上找不到任何关于这种构造多行字符串的方法的参考资料。我不知道它是否正确。我怀疑python是因为反斜杠而忽略了换行符?也许有人可以解释一下。

ubof19bj

ubof19bj5#

这通常是一个注解,但缩进似乎在注解中无效。
在下面的代码中,我展示了在函数定义的上下文中,@ShunYu.的答案与@Superstring的解决方案的比较:

def test() :

    string1='\
The city was bustling with activity as \
people hurried to and fro, going about \
their daily routines.\
\n\
Cars honked their horns, buses roared down the streets, and the air was filled with the sound of chatter and laughter.\
'

    string2=(
    'The city was bustling with activity as '
    'people hurried to and fro, going about '
    'their daily routines.'
    '\n'
    'Cars honked their horns, buses roared down the streets, and the air was filled with the sound of chatter and laughter.'
    )
    print(string1)
    print('\n')
    print(string2)

输出:

城市里一片繁忙,人们来来往往,忙碌着,汽车鸣笛,公交车呼啸,空气中充满了欢声笑语。
城市里一片繁忙,人们来来往往,忙碌着,汽车鸣笛,公交车呼啸,空气中充满了欢声笑语。
@SuperString提供的答案允许字符串在函数中缩进,而@ShunYu.提供的答案似乎需要删除缩进。

相关问题