-3

Im trying to get info from strings that I have parsed. Im trying to get the font size. This is the string Im returning

style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"

Im trying to get 70 from font-size what would the best way to do that be?

Jack Soder
  • 77
  • 1
  • 7

5 Answers5

1

You can use re module for the task:

style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"

import re

print( re.search(r'font-size:\s*(\d+)', style)[1] )

Prints:

70
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Alternatively, you can parse the string to a dictionary. This might be useful if you want to access more than just that property.

style_dict = dict([[a.strip() for a in s.split(':')] for s in style.split(';') if s != ""])
style_dict['font-size']

Gives

'70px'

If you don't want the units:

style_dict['font-size'][:-2]
Dominic D
  • 1,778
  • 2
  • 5
  • 12
1

You can use regular expressions to find what you need

    import re

    style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: ProjectStocksFont; font- 
    size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"

    fontSize = re.findall("font-size: (.+)px",style)[0] # returns '70'

https://www.w3schools.com/python/python_regex.asp

  • While the OP's question uses px as units, there are other valid units for font-size in CSS. This will fail in those other cases. – Michael Ruth Jun 20 '20 at 23:25
1

Using the .split() method is one approach.

You can split the string into a python list to separate each kind of entry in your string. Then you can iterate though your list splitting each sub-string and save your values in a python dictionary.

style = "fill: rgb(0, 0, 0); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"
style_dict = {}
style = style.split("; ")

for item in style:
    key, value = item.split(": ")
    style_dict[key] = value

key = "font-size"
print(style_dict[key])
Tyler Russin
  • 106
  • 4
0

You can use a regex to accomplish this, but it would be better to use some package that understands CSS. Anyways, give this a try:

import re


style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"
font_size = re.match(r'.*font-size: ([^;^a-z]+).*', style)
Michael Ruth
  • 2,938
  • 1
  • 20
  • 27