0

I want to remove all the character after a non-alphanumerical character ('_') within a string. For example:

Petr_;Y -> Petr 
ČEZ_^(České_energetické_závody) -> ČEZ

I tried:

''.join(c for c in mystring if c.isalnum())

But this way I'm stripping off only alphanumerical characters itself.

Help would be appreciated.

Stanislav Jirak
  • 725
  • 1
  • 7
  • 22
  • An efficient way is you can use re module in python to achieve this, >>> from re import split >>> s1 = "ČEZ_^(České_energetické_závody)" >>> split('_', s1)[0] 'ČEZ' – Dhinesh Sunder Ganapathi Jun 28 '21 at 12:26

2 Answers2

3

You may want to use the .split() method on strings.

new_string = your_string.split('_',1)[0]

This way you keep only what's before the fisrt '_'.

zanga
  • 612
  • 4
  • 20
1

Searching the index of first occurrence of "_" will do:

s1 = "Petr_;Y"  
s2 = "ČEZ_^(České_energetické_závody)"

s11 = s1[:s1.index("_")]
s22 = s2[:s2.index("_")]
zwitsch
  • 359
  • 3
  • 9