如何使用 Python 或 GREL 将数字添加到字符串
How to add numbers to a string with Python or GREL
我在需要操作的列中有 >4000 个数字..
它们看起来像这样:
040 413 560 89 或 0361 223240
我怎么把它变成下面的格式:
+49 (040) 41356089 或 +49 (0361) 223240
他们都需要有相同的国家拨号代码+49然后各自的区号放在括号里,有些已经格式正确。
你可以做到这一点。
phone = "456789"
cod = 123
final = str(cod) + phone
结果是"123456789"
我们可以将字符串分成几组:
>>> groups = '040 413 560 89'.split()
>>> groups
['040', '413', '560', '89']
我们可以对组进行切片,赋值给变量,也可以将后面的组连接成一个字符串:
>>> city, number = groups[0], ''.join(groups[1:])
>>> city, number
('040', '41356089')
我们可以格式化一个新字符串:
>>> '+49 ({}) {}'.format(city, number)
'+49 (040) 41356089'
我们可以检查一个数字是否已经以 +
:
开头
>>> '+49 (040) 41356089'.startswith('+')
True
这样做:
ls_alreadycorrected = ['(',')','+49']
str_in = '040 413 560 89' #or apply to list
for flag in ls_alreadycorrected:
if flag not in str_in:
how_many_spaces = str_in.count(' ')
if how_many_spaces > 2:
str_in = str_in.replace(' ','')
str_out = '+049'+' ' + '(' + str_in[:3] + ') ' + str_in[-8:]
else:
str_in = str_in.replace(' ','')
str_out = '+049'+' ' + '(' + str_in[:4] + ') ' + str_in[-6:]
这只是给定了 phone 种类型的数字。对于数字列表,将其放在顶部而不是 str_in
for number in list_of_numbers:
str_in = number
干杯
我在需要操作的列中有 >4000 个数字.. 它们看起来像这样: 040 413 560 89 或 0361 223240
我怎么把它变成下面的格式: +49 (040) 41356089 或 +49 (0361) 223240
他们都需要有相同的国家拨号代码+49然后各自的区号放在括号里,有些已经格式正确。
你可以做到这一点。
phone = "456789"
cod = 123
final = str(cod) + phone
结果是"123456789"
我们可以将字符串分成几组:
>>> groups = '040 413 560 89'.split()
>>> groups
['040', '413', '560', '89']
我们可以对组进行切片,赋值给变量,也可以将后面的组连接成一个字符串:
>>> city, number = groups[0], ''.join(groups[1:])
>>> city, number
('040', '41356089')
我们可以格式化一个新字符串:
>>> '+49 ({}) {}'.format(city, number)
'+49 (040) 41356089'
我们可以检查一个数字是否已经以 +
:
>>> '+49 (040) 41356089'.startswith('+')
True
这样做:
ls_alreadycorrected = ['(',')','+49']
str_in = '040 413 560 89' #or apply to list
for flag in ls_alreadycorrected:
if flag not in str_in:
how_many_spaces = str_in.count(' ')
if how_many_spaces > 2:
str_in = str_in.replace(' ','')
str_out = '+049'+' ' + '(' + str_in[:3] + ') ' + str_in[-8:]
else:
str_in = str_in.replace(' ','')
str_out = '+049'+' ' + '(' + str_in[:4] + ') ' + str_in[-6:]
这只是给定了 phone 种类型的数字。对于数字列表,将其放在顶部而不是 str_in
for number in list_of_numbers:
str_in = number
干杯