I'm working on a Python(3.6) project in which I need to append an integer value to a multiline string.
Here's My code:
for var in list(range(1, no_of_svc + 1)):
svar = str(var)
print(type(svar))
port = type(data['configuration']['svc' + svar]['port']['port'])
print(port)
port = str(data['configuration']['svc' + svar]['port']['port'])
deployments = deployment + '''\n
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: ''' + data['deployment_name'] + '''-''' + data['configuration']['svc' + str(var)]['name'] + '''
labels:
#Project ID
app: ''' + data['configuration']['svc' + str(var)]['name'] + '''
spec:
#Run two instances of our application
replicas: ''' + data['configuration']['svc' + str(var)]['replicas'] + '''
template:
metadata:
labels:
app: ''' + data['configuration']['svc' + str(var)]['name'] + '''
spec:
#Container details
containers:
- name: ''' + data['configuration']['svc' + str(var)]['versions']['v1']['name'] + '''
image: ''' + data['configuration']['svc' + str(var)]['versions']['v1']['image'] + '''
imagePullPolicy: Always
#Ports to expose
ports:
- containerPort: ''' + port + '''
'''
As you can see in the code above I have converted port
to string and even the output of print(type(svar))
and print(port)
is <class 'str'>
but still it's not working.
Here's the error message:
- containerPort: ''' + port + '''
TypeError: must be str, not int
I have turned it by using the
format
method and it's working:
no_of_svc = int(data['configuration']['no_of_svc'])
deployment = ''
deployments = ''''''
for var in list(range(1, no_of_svc + 1)):
deployments = deployment + '''\n
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: {}
labels:
#Project ID
app: {}
spec:
#Run two instances of our application
replicas: {}
template:
metadata:
labels:
app: {}
spec:
#Container details
containers:
- name: {}
image: {}
imagePullPolicy: Always
#Ports to expose
ports:
- containerPort: {}
'''.format(data['deployment_name'] + '-' + data['configuration']['svc' + str(var)]['name'],
data['configuration']['svc' + str(var)]['name'],
data['configuration']['svc' + str(var)]['replicas'],
data['configuration']['svc' + str(var)]['name'],
data['configuration']['svc' + str(var)]['versions']['v1']['name'],
data['configuration']['svc' + str(var)]['versions']['v1']['image'],
data['configuration']['svc' + str(var)]['port']['port'])
print(deployments)
What can be wrong?
Use format
to put value of port
in your string.
See this:-
>>> port = 'my string1'
>>> str1 = ''' this is the second string and here is {} '''.format(port)
>>> str1
' this is the second string and here is my string1 '