Can you concatenate a variable name in python?

I need to check variables looking like this:

if name1 != "":
    [do something]

Where the number right after "name" is incremented between 1 and 10.

Do I need to write the test ten times or is there a way [without using an array or a dict] to "concatenate", so to speak, variable names?

I'm thinking about something like this:

for i in range[10]:
    if "name" + str[i] != "":
        [do something]

Edit: I can't use a list because I'm actually trying to parse results from a Flask WTF form, where results are retrieved like this:

print[form.name1.data]
print[form.name2.data]
print[form.name3.data]
etc.

Rao

20.2k10 gold badges55 silver badges73 bronze badges

asked Apr 27, 2016 at 19:13

4

  1. Use a list, such as:

    names = ['bob', 'alice', 'john']
    

    And then iterate on the list:

    for n in names:
      if n != "":
         [do something]
    
  2. or you could have a compounded if statement:

    if [name1 != "" or name2 != "" or name3 != ""]
    

The best solution would be to use solution #1.

Bhargav Rao

47.2k27 gold badges121 silver badges137 bronze badges

answered Apr 27, 2016 at 19:19

MileanMilean

8688 silver badges16 bronze badges

1

If you cannot use a list or a dict, you could use eval

for i in range[10]:
    if eval["name" + str[i]] != "":
        [do something]

answered Apr 27, 2016 at 19:18

FrancescoFrancesco

3,8912 gold badges19 silver badges28 bronze badges

2

First of all, your app have invalid logic. You should use list, dict or your custom obj.

You can get all variable in globals. Globals is a dict.

You can do next:

for i in range[10]:
    if globals[].get['name%d' % i]:
        # do something

answered Apr 27, 2016 at 19:22

mrvolmrvol

2,25915 silver badges19 bronze badges

In computing, string combining is an overall common process. Concatenating strings in Python may be expressed in a variety of ways. This tutorial will look at various methods for concatenating strings inside a Python application. To concatenate strings with a delimiter, we may use the join[] method. It is beneficial to have a character sequence, such as a list or perhaps a tuple of characters. Then, use the join[] method with an empty string whenever you don’t want a delimiter. Use these methods according to your needs. Whenever concatenation requires any formatting, just use format[] as well as f-string functions. It’s worth noting that f-string only works with Python 3.6 and higher. Let’s have a look at each one of them.

Example 01: Concatenate With “+” Operator

Log in from the Ubuntu login panel and open the terminal from the applications via “Ctrl+Alt+T”.  After opening it, let’s create a new python file “one.py” via the “touch” query as follows:

The file has been created. Open it from the file explorer by navigating to the “Home” directory. Double-tap to open the file and write out the following code in your newly created file. This code contains two string-type variables v1 and v2, with some value in both of them. The variable “name” has been initialized to concatenate both the variables v1 and v2 using the “+” operator within them. After that, the print statement has been used to print the concatenated variable “name”. Save your file with “Ctrl+S” and quit it.

Let’s execute the file by using the “python3” query in the shell below. You will see that it will show a concatenated string e.g., “Aqsa Yasin”, made from two string variables:

The “+” sign acts differently for integer-type variables. This operator sums up the integers instead of concatenating them. For example, let’s update the value of both variables v1 and  v2 with integers and use the “+” sign to merge them. When we print the resultant value, it shows the sum of both variables instead of the concatenated value. Save the file with the “Ctrl+S” shortcut and leave it:

Upon execution, you can see that the output is an integer sum-up value:

Let’s use one integer type and one string type variable in the concatenation example. Update the code with the following script having two variables e.g., string and integer. Use the “+” operator to concatenate both and print them:

After saving our file with “Ctrl+S”, we will close our file and navigate to the terminal again. Execution of this code will be done by the stated command below. Unfortunately, the output for this code will lead you to an error because the “+” sign doesn’t work on two different kinds of data types to concatenate them.

Example 02: Concatenate With Join[]

It’s time to have a look at a different example for concatenation. We will be using the join[] function to concatenate two strings. Update the code as shown below. We have two string-type variables v1 and v2, defined in the code. We have concatenated both variables with the join function. Upon passing into its parameter, they become concatenated and then printed out:

Save the file and open your terminal. Execute the code with the “python3” query as below. You will see that it shows the concatenated result “Aqsa Yasin” of variables v1 and v2 using the join method:

Example 03: Concatenate With “%” Operator

Let’s have another example of concatenation. This time, we will be utilizing the percentage operator in our code to do so. We have taken two string-type variables v1 and v2, with different values. After that, we have created another variable, “new” and defined a percentage format along with the sign “%”. We have also given both the variables in their parameters. At last, we have printed this resultant value of string concatenated by the percentage operator in a print statement. Save your file and click on the cross sign to close it:

Upon execution, you can see it working properly and showing the concatenated new string from both two variables using a percentage operator:

Example 04: Concatenate With Format Function

Now, we will be using another function to concatenate two new variables v1 and v2. We defined a format for this function in the newly created variable “new” and passed both the variables v1 and v2 in its parameters. Last, we have given this freshly concatenated variable “new” in the print statement to be printed out shortly.

After saving and closing the file, let’s begin with the execution of our updated code. We have been using the very same instruction in the shell for execution. The output for the execution of this code shows the concatenated value “Linux-Python” of both the variables that have been saved into the variable “new”.

Example 05: Concatenate With F-string

The last and the unique example for concatenating two string-type variables is via f-string.  We have initialized two new variables v1 and v2, with string type values in both of them. After this, we have initialized another variable, “new”, and defined f-string type format in it with variables v1 and v2 within its format. In the last line of code, we have used the print statement in which we have passed the concatenated variable “new” to print it in concatenated format.

Save your file and close it once again. Now open the terminal and execute the code file via the “python3” keyword along with the name of a file “one.py”. The output presents the concatenated value of variable “new” while using the f-string format of concatenation.

Conclusion:

We have learned five methods to concatenate the strings in our examples using this tutorial guide. I hope this article will better demonstrate the process of Python String Concatenation

About the author

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

How do you concatenate a variable name with a string in Python?

Example 01: Concatenate With “+” Operator This code contains two string-type variables v1 and v2, with some value in both of them. The variable “name” has been initialized to concatenate both the variables v1 and v2 using the “+” operator within them.

How do you concatenate names in Python?

The + operator lets you combine two or more strings in Python. This operator is referred to as the Python string concatenation operator. The + operator should appear between the two strings you want to merge. This code concatenates, or merges, the Python strings “Hello ” and “World”.

How do you concatenate two variables in Python?

Using '+' operator Two strings can be concatenated in Python by simply using the '+' operator between them. More than two strings can be concatenated using '+' operator.

Can you concatenate variables?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.

Chủ Đề