0

I have hostname of format xxxxxxxx-abcdxxxxx the x is not a set number so can't use print text[10:14] because I don't have a set location, the only pattern is 4 chars after -.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Victor
  • 427
  • 1
  • 6
  • 19

2 Answers2

6

Assuming your first string is

s = "xxxxxxxx-abcdxxxxxxxxx"

you just do:

s.split("-",1)[1][:4]

which splits s into two strings in an array, ['xxxxxxxx','abcdxxxxxxxxx'] and you get the result by taking the splicing of the 2nd array from index 0 to 4.

abcd
Patrick Yu
  • 972
  • 1
  • 7
  • 19
5

Option 1

Get the index of the dash and select from +1 to +5:

a = 'xxxxxxx-abcdxxxxxxx'
i = a.index('-')
print(i[i+1:i+5])

Option 2

Use the split function and then get the first 4 values of the second element.

a = 'xxxxxxx-abcdxxxxxx'
print(a.split('-')[1][:4])

To see if a string is alphabetic, simply call the isalpha function:

str.isalpha()

It will return true or false based on result.

m_callens
  • 6,100
  • 8
  • 32
  • 54