[英]Reformatting String in Python
I am looking for some help on the following reformatting problem.我正在寻找有关以下重新格式化问题的帮助。
I have 3 random characters that appear joined in my data set.我有 3 个随机字符出现在我的数据集中。 I need to separate the first character with a space from the other two, then insert a '/' between remaining two.我需要用空格将第一个字符与其他两个字符分开,然后在剩下的两个字符之间插入一个“/”。 ie IE
random_char = '713' expected_result = '7 1/3' random_char = '713' 预期结果 = '7 1/3'
Assuming your string is always exactly three characters, here is one solution:假设您的字符串始终正好是三个字符,这是一种解决方案:
random_char = '713'
result = '{} {}/{}'.format(*random_char)
print(result)
>>> '7 1/3'
The {}
are placeholders, and the *random_char
'unpacks' the characters of your original string into the three placeholders. {}
是占位符, *random_char
将原始字符串的字符“解包”为三个占位符。
random_char = '713'
# using unary '*' as the unpack operator
print('{} {}/{}'.format(*random_char))
# is here equivalent to
print('{} {}/{}'.format(random_char[0], random_char[1], random_char[2]))
You can simply separate string into characters and form as you want to use them.您可以根据需要将字符串简单地分成字符和形式。 in your case it can be formed as:在您的情况下,它可以形成为:
a = '732'
print(a[0] + ' ' + a[1] + '/' + a[2])
output will be 7 3/2
输出将为7 3/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.