Home > Net >  How to get Python to interpret a string and populate variables from string data
How to get Python to interpret a string and populate variables from string data

Time:07-28

I am trying to create a python script that queries my helpdesk ticket, parses the HTML, and outputs the parsed information into an XML or JSON file.

I have gotten to the point where the script outputs a string, here is an example of the string:

EMPLOYEE INFORMATION
Name: EmployeeName
Employee Type: Salaried/Hourly
Department: DepartmentName
Department Number: IntegerValue
Employee Title: EmployeeTitle
Supervisor Name: SupervisorName

FACILITIES INFORMATION
Location: OfficeLocation

SECURITY INFORMATION
Access card required?: Boolean
Copy access card from: CopyFromUser
Elevated access justification: Boolean

What will I need to do in order to get the information in this string populated into variables such as

EmployeeName = string
DepartmentName = string
AccessCardRequired = boolean
DepartmentNumber = int 

CodePudding user response:

There are different libraries that exist to help you to achieve this depending on the structure of the string you want to parse. For instance configparser to parse simple text or beautifulsoup for html.

If the string is in the format you described above:

  • one variable per line
  • variable_name: value

You can just use configparser which comes natively with Python. https://docs.python.org/3/library/configparser.html

If the text is in html, you can check beautifulsoup. https://www.crummy.com/software/BeautifulSoup/bs4/doc/

CodePudding user response:

Concentrate a variable with a string by using character.
Example:

variable = "Text 2"

print("Text 1 "   variable   " Text 3")

Output:

Text 1 Text 2 Text 3

If your variable type is an integer, it needs to convert it to a string before concatenation. To convert, we'll use the str() function.

variable = 2

# insert a variable into string using concatenation
print("One "   str(variable)   " Three")

Output:

One 2 Three
  • Related